我有這樣的物體的背景關系:
public class CompanyContext : DbContext
{
public DbSet<StoreModel> Stores { get; set; }
// Other entities
}
public class DepartmentContext : DbContext
{
public DbSet<OrderModel> Orders { get; set; }
// Other entities
}
public class StoreModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<OrderModel> ReceivedOrders { get; set; }
public virtual ICollection<OrderModel> PreparedOrders { get; set; }
public virtual ICollection<OrderModel> IssuedOrders { get; set; }
}
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public StoreModel GettingStore { get; set; }
public StoreModel PreparingStore { get; set; }
public StoreModel IssuanceStore { get; set; }
}
例如,用戶在 storeA 下訂單,但想在 storeC 中接收,它的訂單將在 storeB 中準備。我需要關于商店收到/準備/發出的訂單的統計資訊。
當我嘗試創建遷移時,EF 拋出例外"Unable to determine the relationship represented by navigation 'OrderModel.GettingStore' of type 'StoreModel'"并且"Unable to determine the relationship represented by navigation 'StoreModel.IssuedOrders' of type 'ICollection<OrderModel>'". 如果我理解正確,這是因為物體是在不同的背景關系中定義的。
現在我只使用下一個模型:
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public Guid GettingStoreId { get; set; }
public Guid PreparingStoreId { get; set; }
public Guid IssuanceStoreId { get; set; }
}
這很好用,但也許有一些選項允許使用導航屬性創建這樣的結構,并在來自不同背景關系(資料庫)的這些物體之間建立正確的關系。
uj5u.com熱心網友回復:
首先,不同資料庫的映射沒有放在不同應用程式格式的表中,所以認為您有一個應該在應用程式中很好定義的域,這樣您的應用程式映射就會像這樣:
public class DomainNameContext: DbContext
{
public DomainNameContext(): base()
{
}
public DbSet<StoreModel> Stores { get; set; }
public DbSet<OrderModel> Orders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// config mapping methods
}
}
另一件事,您使用的關系不起作用,因此您不能在同一個類中重復 Orders,因為這不是一個 -> 很多,此陳述句意味著 StoreModel 行可以在 OrderModel 中有很多行方式是這樣的
public class OrderModel
{
public Guid Id { get; set; }
public string Details { get; set; }
public Guid StoreModeId { get; set; } // this part will show the entity framework that this is the fk it will correlate
public StoreModel StoreModel { get; set; }
}
public class StoreModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<OrderModel> OrderModels { get; set; }
}
看到如果你想要有許多 StoreModel 與許多 OrderModel 相關,那么你需要使用 many -> many 微軟檔案預計也會使用
很好地在其背景關系中映射它,在 OnModelCreating 中必須像這樣使用它的映射:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// config mapping methods
modelBuilder.Entity<StoreModel>()
.HasMany<OrderModel>(g => g.OrderModels )
.HasForeignkey<Guid>(s => s.StoreModeId )
}
你可以看看微軟檔案在這里輸入鏈接描述,在這里輸入鏈接描述
現在,如果您需要在背景關系之間進行映射,您將不得不使用 dapper 在單獨的基礎上進行單獨的查詢,該物體在此鏈接中支持該查詢 在此處輸入鏈接描述 ,然后您可以進行必要的內部連接,以便您可以使用它但是本來這不存在,我建議您重新考慮您的資料庫,以便它對關系模型更有意義,也許為您的 StoreModel 和 OrderModel 放置型別,以便您可以使用我想要的型別 GettingStore、PreparingStore、IssuanceStore 的方式使用列舉,使其明確
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/522473.html
