EF Code First - Two Tables, Two relationships
i'm with a trouble;
For initial imagine that we have an entity Member, and Member has Projects..
If you ask: Do projects have members? Yes they have...
Members (N*) <-> Project (N*) - so is a n-n-relationship.
But in my domain application i wanna say too that one Member is responsible for N projects, and one Project has one Member..
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; }
}
For ProjectsWorker property in Worker will be a N-N relationship between Member and Project, but with this (the EF framework only creates for me the 1-way relashionship)
My question is... who can i a map these two relationships with code-first. I was using DatabaseFirst, and now with code-first it appears to be very powerful but restrict me a little now.
You must tell EF which relationships belong together. You can do this either with data annotations ...
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; }
// ...
}
(I believe the InverseProperty
attribute is only necessary on one side of the relationship, but I am not sure.)
... or in 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");
});
}
精彩评论