2014-09-21 19 views
0

我想分享我的CustomersVendors之間的Contacts實體。如何建立表格以便由0到多個關係的其他表共享?

Customers可以有很多Contacts

Vendors可以有很多Contacts

...但是當我做了我的模型我跑到那裏,現在我必須既CustomerIdVendorId提供給每個接觸的問題。

我會發布我的模型的圖像,但我沒有10分。

回答

0

Customers可以有多個聯繫人

Vendors可以有多個聯繫人

正如你所說,而不是似乎CustomersContacts之間和ContactsVendors之間的關係是零或一對多。

所以,你可以把CustomerIdVendorIdnullable:我使用模型的第一

public class Contact 
{ 
    public int Id { get; set;} 
    public int? CustomerId {get; set;} 
    public int? VendorId {get; set;} 
    // other properties 
} 

public class Customer 
{ 
    public int Id { get; set;} 
    public ICollection<Contact> Contacts {get; set;} 
    //other properties 
} 

public class Vendor 
{ 
    public int Id { get; set;} 
    public ICollection<Contact> Contacts {get; set;} 
    //other properties 
} 
+0

。這兩個屬性都設置爲空。我改爲0/1(客戶/供應商)-many(聯繫人)。當我首先測試數據庫時,EF將可空屬性設置爲NONE。它現在可以工作,並且沒有任何錯誤,但我想知道這是否正常共享表格之間的「聯繫人」,或者是否有更多的「標準」方式來執行此操作。 – user3928549 2014-09-21 05:41:53

+0

在您的項目中,幾個客戶或供應商是否有聯繫?因爲採用這種結構,您不能將同一聯繫人鏈接到多個客戶或供應商。 – Peter 2014-09-21 05:47:28

+0

不,我不認爲如果聯繫由客戶和供應商共享 - 是否應該重新考慮這一點? – user3928549 2014-09-21 05:50:23

0

如果您正在處理多對多關係,則很可能必須使用junction table

這意味着具有與每個兩列兩個附加表:

  • VendorsContacts與主鍵::廠商ID,使用ContactID
  • CustomersContacts與主鍵::客戶ID,使用ContactID

這些表的主鍵需要是compound,即兩個鍵一起作爲單個主鍵。在SQL Server中,通過用CTRL標記兩列並創建主鍵來實現。你會注意到他們都被標記爲主要。

EntityFramework不會爲聯結表創建實體類,您將通過yourCustomer.Contacts和類似的yourVendor.Contacts直接訪問給定客戶/供應商的聯繫人。

相關問題