2015-12-30 122 views
1

我有三個表實體框架的多表關聯

EVENT - PERSON - COMPANY 

我需要有一個關係,多到許多使用這些表。一個事件可以有一個或多個「客戶」,可以是個人或公司。通常情況下,不使用ORM,使用SQL,這將是這樣的:

EVENT 
---- 
id 
name 

CLIENTEVENT 
----------- 
id 
clientid 
clienttype -- person or company 


PERSON 
----------- 
id 
name 
lastname 
... 


COMPANY 
------- 
id 
name 

請問這個方法可以使用實體框架被複制?我很新的使用EF,所以我將不勝感激所有幫助你可以給我。我使用存儲庫模式,遵循這種方法http://www.codeproject.com/Articles/838097/CRUD-Operations-Using-the-Generic-Repository-Pat

回答

0

我建議你,而不是clientid和clienttype做另外兩列:personID和companyID。模型將如下所示:

public class Event  
{ 
    public int ID { get; set; } 
    public string name { get; set; } 

    public virtual ICollection<CLIENTEVENT> links { get; set; } 
} 

public class Company 
{ 
    public int ID { get; set; } 
    public string name { get; set; } 

    public virtual ICollection<CLIENTEVENT> links { get; set; } 
} 

public class PERSON 
{ 
    public int ID { get; set; } 
    public string name { get; set; } 
    public string lastname { get; set; } 

    public virtual ICollection<CLIENTEVENT> links { get; set; } 
} 

public class CLIENTEVENT 
{ 
    public int ID { get; set; } 

    public virtual PERSON person { get; set; } 
    public int? personID { get; set; } 

    public virtual Company company { get; set; } 
    public int? companyID { get; set; } 

    public virtual Event event1 { get; set; } 
    public int? event1ID { get; set; } 
} 
+0

是的,你可以保持clientid和clienttype列,但它不會是外鍵,你將失去這個實體在你的數據庫(約束)和代碼(屬性 - 「鏈接」)之間的舒適關係。只有在PERSON和COMPANY之外還會出現另一個具有相同關係的實體纔有意義。 –

0

使用EF Code First,您不必處理像ClientEvent這樣的連接表。你可以簡單地寫:

public class Event  
{ 
    public int Id { get; set; } 

    public string Name { get; set; } 

    public virtual ICollection<Company> Companies { get; set; } 

    public virtual ICollection<Person> Persons { get; set; } 
} 

public class Company 
{ 
    public int Id { get; set; } 

    public string Name { get; set; } 

    public virtual ICollection<Event> Events { get; set; } 
} 

public class Person 
{ 
    public int ID { get; set; } 

    public string Name { get; set; } 

    public string Lastname { get; set; } 

    public virtual ICollection<Event> Events { get; set; } 
} 

試試這個代碼,你會看到EF創建兩個鏈接表(EventPerson和EventCompany)。現在,客戶類型是您閱讀的集合(someEvent.PersonssomeEvent.Companies),您還可以輕鬆獲取鏈接到特定人員或公司的事件。

About many-to-many with EF