2014-01-23 32 views
0

我總是很難與這一個。這是一個簡單的問題,我知道我希望數據庫最終看起來如何,但我不知道如何到達那裏。我有以下實體:實體框架和設置查找/列表以及m2m關係

組織

public class Organization 
{ 
    [Key] 
    public int OrganizationId { get; set; } 
    public string Name { get; set; } 
    public ICollection<Industry> OrgIndustries { get; set; } 
} 

行業

public class Industry 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

用戶的情況是,一個組織可以有1個或多個行業它是一個部分(即高等教育和信息技術)。爲了實現應用目的,我希望行業表作爲不斷增加的行業名單,只有名稱和編號,沒有FK。所以,你知道,一個簡單的查找表。除此之外,我還需要一種方法來跟蹤組織所屬的行業。在數據庫中它會是這個樣子(僞):

[OrgTable] 
    ColId 
    Col-OrgIndustryTableFK 
    ... 

[OrgIndustryTable] 
    ColId 
    ColOrgId 
    ColIndustryId 

[Industry] 
    ColId 
    ColName 

我有它設置現在創建了FK的Org_Id在工業路表。不是我想要的。我怎樣才能得到我想要的東西?

回答

1

如果你想堅持只用數據說明,一個簡單的屬性添加到Industry引用的Organization個集合:

public class Industry 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    // don't forget to make it virtual if you want to option to lazy load 
    public virtual ICollection<Organization> IndustryOrgs { get; set; } 
} 

如果你不想將該屬性添加到Industry類,你可以通過流暢的API配置:

modelBuilder.Entity<Organization>() 
    .HasMany(o => o.OrgIndustries) 
    // configures the relationship to be many:many 
    // without a navigation property on the other 
    // side of the relationship 
    .WithMany();