2014-01-23 29 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();