我正在使用Code方法创建我的数据库,到目前为止,这种方法工作得很好。然而,我有一个小问题,EF6似乎无法理解,或者我做错了。
我有Project
类,它有一个属性CreatedBy
类型为Person
,另一个属性Members
类型为ICollection<Person>
;
public class Project
{
// ...
public Person CreatedBy { get; set; }
public virtual ICollection<Person> Members { get; set; }
}
在类Person
中,我添加了以下属性:
public virtual ICollection<Project> Projects { get; set; }
告诉EF6,这两个类之间应该有多到多的关系。
如果我在Visual中运行了一个Add-Migration
和Update-Database
,并在Project
类中注释了CreatedBy
,那么将会在数据库中创建一个Project <-> Person
表。
如果我取消对CreatedBy
属性的注释并再次运行相同的脚本,那么Project <-> Person
表就会被删除,Project
和Person
表都会得到一个新列,在这两个表之间有一个ForeignKey,将其更改为1到1的关系。
我如何首先使用代码在我的Project
和Person
类之间建立关系,这样我就可以同时创建一对多(1个人可以创建多个项目)和多到多(可以将许多人添加到许多项目中)?
发布于 2015-01-20 16:32:34
您需要为配置实体使用Fluent API:
class ProjectConfiguration : EntityTypeConfiguration<Project>
{
public ProjectConfiguration()
{
HasRequired(e => e.CreatedBy).WithMany(); // one-to-many
HasMany(e => e.Members).WithMany(); //many-to-many
}
}
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProjectConfiguration());
}
}
关于Fluent API:http://msdn.microsoft.com/en-us/data/jj591617.aspx的更多细节
使用Fluent API:http://msdn.microsoft.com/en-us/data/jj591620配置关系
发布于 2015-01-20 16:06:47
我还没有验证这一点,但是如果为您创建的对象指定和显式外键,就足以区分这两种不同的关系:
// make nullable if CreatedBy is not required
[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
public Person CreatedBy { get; set; }
https://stackoverflow.com/questions/28047631
复制相似问题