【问题标题】:Entity Framework Code First Mapping实体框架代码优先映射
【发布时间】:2011-08-08 22:02:22
【问题描述】:

我有两个类,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; }
}

提前通知!

【问题讨论】:

    标签: c# mapping entity-relationship ef-code-first entity-framework-4.1


    【解决方案1】:

    我会使用流畅的 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 不需要在关系的两边,但它的定义更清晰。

    【讨论】:

    • @Ladislav Mrnka 你能解释一下 WillCascadeOnDelete 和 WithRequired。请。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2011-04-21
    • 2012-05-18
    • 1970-01-01
    相关资源
    最近更新 更多