簡體   English   中英

實體框架6,具有對多個其他表的引用的表

[英]Entity Framework 6, table with references to multiple other tables

我有一個項目,其中有很多表,需要地址:

  • 顧客
  • 訂購
  • 供應商
  • ...還有很多。

我們正在嘗試使用如下通用地址表來代替CustomerAddress,OrderAddress和VendorAddress表:

AddressId  (PK, int, identity, not null)
AddressType (int, not null, poss values: Customer, Order, Vendor, etc..)
ForeignKeyId (int, not null)
Name
Street
City
etc...

和一個客戶表:

CustomerId (PK, int, identity, not null)
...other customer information...

如果我有一個客戶(CustomerId = 56),那么可能會有這樣的地址記錄:

AddressId (some number)
AddressType = 1 (Customer)
ForeignKeyId = 56
Name, Street, City

這一切都很好。

但是,問題出在我要向系統中添加新客戶的時候。 在EF中,我認為這意味着我必須添加客戶SaveChanges() ,然后分別添加地址。

Customer c = new Customer { ... };
context.Customer.Add(c);
context.SaveChanges();    // In order to get the CustomerId to be filled in
Address a = new Address { AddressType = 1, ForeignKeyId = c.CustomerId };
context.Address.Add(a);
context.SaveChanges();

這在代碼結構上引起了兩個問題。 首先,事情發展的方式是,我們可能不會在同一位置添加客戶和地址。 其次,更重要的是,這需要兩個SaveChanges(),這意味着我們不再需要事務(或者我們必須進行自己的事務並隨身攜帶)。

我想做的更多是這樣的:

Customer c = new Customer { ... };
context.Customer.Add(c);
Address a = new Address { AddressType = 1 };
context.Address.Add(a);
// Somehow magic happens and Address can be associated with
// Customer as soon as we have a CustomerId assigned.
context.SaveChanges();  

我知道沒有魔術,但是我有辦法通過一個SaveChanges()完成我想要的嗎?

編輯 :如果相關,這是數據庫優先EF。

如果數據庫在表之間沒有關系,則必須先添加()每個對象,然后再保存(ChangeChanges)()。

兩者之間的關系是什么,例如一對一,一對多?

建立關系可以讓您這樣編寫代碼:

Customer c = new Customer
{
    ...
    Address = new Address { AddressType = 1 }
};

context.Customer.Add(c);
context.SaveChanges();

如果您尚未建立數據庫關系並且無法建立數據庫關系,則應該能夠在EM中虛擬化該關系。

在您的Context類文件中,修改

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //default statement
    //throw new UnintentionalCodeFirstException();

    //establish the one-to-zero-or-one relation
    modelBuilder.Entity<Customer>()
        .HasOptional(c => c.Address);
}

將適當的屬性添加到您的客戶和地址類。 以一對一關系為例。

public virtual Address Address {get; set;} public virtual Address Address {get; set;}客戶和public virtual Customer Customer {get; set;} public virtual Customer Customer {get; set;}在地址中

我將很快更新OnModelCreating()。 我有個會議要參加。 如果還有其他任何內容,只需將其放入評論中(希望我不太煩惱)。

編輯請參閱此SO答案以建立關系。

編輯2 IRT DB首先,只要表在相同的上下文中,您只需要一次SaveChanges()。 為確保整個DAO的上下文相同,請在實例化DAO時初始化上下文。

private DbEntities db = new DbEntities();

然后,您將始終使用該db上下文實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM