我遇到了麻烦;
初步想象我们有一个实体成员,而成员有项目......
如果你问:项目是否有会员?是的,他们有......
成员(N *)< - >项目(N *) - 这是一个n-n关系。
但在我的域名申请中,我也想说一个会员负责N个项目,一个项目有一个会员......
public class Member : User
{
public virtual ICollection<Project> ProjectsResponsable { get; set; }
public virtual ICollection<Project> ProjectsWorker { get; set; }
}
public class Project
{
public virtual int ProjectID { get; set; }
public virtual String Name { get; set; }
public virtual bool Enabled { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual String Description { get; set; }
public virtual Member Responsable { get; set; }
public virtual ICollection<Member> Workers { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
}
对于Projects中的ProjectsWorker属性将是Member和Project之间的N-N关系,但是这样(EF框架只为我创建单向关系)
我的问题是......我可以用代码优先映射这两种关系。 我正在使用DatabaseFirst,现在以代码优先,它似乎非常强大,但现在限制我一点。
答案 0 :(得分:1)
你必须告诉EF哪些关系属于一起。您可以使用数据注释...
执行此操作public class Member : User
{
[InverseProperty("Responsable")]
public virtual ICollection<Project> ProjectsResponsable { get; set; }
[InverseProperty("Workers")]
public virtual ICollection<Project> ProjectsWorker { get; set; }
}
public class Project
{
public virtual int ProjectID { get; set; }
// ...
[InverseProperty("ProjectsResponsable")]
public virtual Member Responsable { get; set; }
[InverseProperty("ProjectsWorker")]
public virtual ICollection<Member> Workers { get; set; }
// ...
}
(我相信InverseProperty
属性只在关系的一方是必要的,但我不确定。)
...或在Fluent API中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Member>()
.HasMany(m => m.ProjectsResponsable)
.WithOptional(p => p.Responsable) // or WithRequired(...)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Member>()
.HasMany(m => m.ProjectsWorker)
.WithMany(p => p.Workers)
.Map(a => {
a.ToTable("MemberProjects");
a.MapLeftKey("MemberID");
a.MapRightKey("ProjectID");
});
}