6

我有两个类,Group类与User类具有多对多的关系(表示用户所属的组),然后该组也与用户具有一对多的关系类(代表一个组的所有者)。实体框架代码优先映射

如何映射此?

public class User 
{ 
    public int Id { get; set; } 
    public string Avatar { get; set; } 
    public string Name { get; set; } 
    public string Message { get; set; } 

    public virtual ICollection<Group> OwnedGroups { get; set; } 
    public virtual ICollection<Group> Groups { get; set; } 
} 

public class Group 
{ 
    public int Id { get; set; } 
    public DateTime CreateDate { get; set; } 
    public DateTime ModifyDate { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public bool System { get; set; } 
    public int ViewPolicy { get; set; } 
    public int JoinPolicy { get; set; } 
    public string Avatar { get; set; } 
    public int Order { get; set; } 
    public int GroupType { get; set; } 

    public virtual User Owner { get; set; } 
    public virtual ICollection<User> Members { get; set; } 
} 

tks提前!

回答

5

我会用流利的API:

public class Context : DbContext 
{ 
    public DbSet<User> Users { get; set; } 
    public DbSet<Group> Groups { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Entity<User>() 
        .HasMany(u => u.Groups) 
        .WithMany(g => g.Members); 

     modelBuilder.Entity<User>() 
        .HasMany(u => u.OwnedGroups) 
        .WithRequired(g => g.Owner) 
        .WillCascadeOnDelete(false); 
    } 
} 

这也应该是可能的数据注释:

public class User 
{ 
    ... 

    [InverseProperty("Owner")] 
    public virtual ICollection<Group> OwnedGroups { get; set; } 
    [InverseProperty("Members")] 
    public virtual ICollection<Group> Groups { get; set; } 
} 

public class Group 
{ 
    ... 

    [InverseProperty("OwnedGroups")] 
    public virtual User Owner { get; set; } 
    [InverseProperty("Groups")] 
    public virtual ICollection<User> Members { get; set; } 
} 

InverseProperty不需要对关系的双方,但它确实定义清晰。

+1

优秀!!! tks – boossss 2011-04-19 18:49:53

+0

@Ladislav Mrnka可以解释WillCascadeOnDelete和WithRequired。 PLZ。感谢名单! – 2011-08-11 19:24:41