Sql 实体框架和设置查找/列表表以及m2m关系
我总是很难接受这个。这是一个简单的问题,我知道我希望数据库最终看起来如何,但我不知道如何实现。我拥有以下实体: 组织机构Sql 实体框架和设置查找/列表表以及m2m关系,sql,entity-framework,ef-code-first,Sql,Entity Framework,Ef Code First,我总是很难接受这个。这是一个简单的问题,我知道我希望数据库最终看起来如何,但我不知道如何实现。我拥有以下实体: 组织机构 public class Organization { [Key] public int OrganizationId { get; set; } public string Name { get; set; } public ICollection<Industry> OrgIndustries { get; set; } }
public class Organization
{
[Key]
public int OrganizationId { get; set; }
public string Name { get; set; }
public ICollection<Industry> OrgIndustries { get; set; }
}
用户案例是一个组织可以有一个或多个它所属的行业(即高等教育和信息技术)。出于应用程序的目的,我希望Industry表作为一个不断增长的行业列表,只包含一个名称和id,而不包含FKs。所以,你知道,一个简单的查找表。除此之外,我还需要一种方法来跟踪该组织所属的行业。在数据库中,它看起来像这样(psuedo):
现在,我的设置方式为行业表中的组织Id创建了FK。不是我想要的。如何设置我想要的内容?如果您只想使用数据注释,只需向
行业添加一个属性,引用组织的集合即可:
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; }
}
[OrgTable]
ColId
Col-OrgIndustryTableFK
...
[OrgIndustryTable]
ColId
ColOrgId
ColIndustryId
[Industry]
ColId
ColName
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; }
}
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();