实体框架代码优先:自定义映射

时间:2011-08-11 13:03:02

标签: c# entity-framework entity-framework-4 entity-framework-4.1 entity-relationship

public class User
{
   public int Id {get;set;}

   public string Name {get;set}

   public ICollection<User> Followers {get;set;}
   public ICollection<User> Following {get;set;}
}

我的模型如上所示,实体框架自动创建一个表格,并在数据库中使用行UserUserUser_ID User_ID1来映射此模型。我想自己映射那个表和行。

我怎么能这样做,Thanx !!

2 个答案:

答案 0 :(得分:2)

Scott Gu's blog关于Many-valued Associations

  

多对多关联   Category和Item之间的关联是多对多的   关联,如上面的类图所示。多对多   关联映射隐藏了中间关联表   应用程序,因此您不会在您的应用程序中结束不需要的实体   领域模型。也就是说,在一个真实的系统中,你可能没有   因为我的经验是多对多的关联,所以几乎有   总是必须附加到每个链接之间的其他信息   关联实例(例如添加项目的日期和时间)   到一个类别)并且表示此信息的最佳方式是   通过中间关联类(在EF中,你可以映射   关联类作为实体并映射两个一对多关联   任何一方。)。

     

在多对多关系中,连接表(或链接表,如某些   开发人员称之为)有两列:类别的外键   和项目表。主键是两列的组合。 在EF   代码优先,可以自定义多对多关联映射   一个流畅的API代码,如下所示:

    class ItemConfiguration : EntityTypeConfiguration<Item> {
    internal ItemConfiguration()
    {
        this.HasMany(i => i.Categories)
            .WithMany(c => c.Items)
            .Map(mc =>
            {
                mc.MapLeftKey("ItemId");
                mc.MapRightKey("CategoryId");
                mc.ToTable("ItemCategory");
            });
    } }

在您的DbContext中注册此配置(您正在使用DbContext api吗?),如下所示:

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

    modelBuilder.Configurations.Add(new ItemConfiguration());
  }
祝你好运,希望有这个帮助!

答案 1 :(得分:2)

要将实体映射到自身,您可以执行类似这样的操作

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().HasMany(u => u.Followers)
        .WithMany().ForeignKey(u => u.FollowerId);

    base.OnModelCreating(modelBuilder);
}

虽然没有看到你的数据库模型很难说,以及你如何将关注者与用户实际联系起来。

相关问题