c# - Entity Framework 代码优先 : Custom Mapping

标签 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;}
}

我的模型如上所示, Entity Framework 自动在数据库中创建一个表和UserUser,其中包含行User_IDUser_ID1来映射此模型。我想自己映射该表和行。

我该怎么做,谢谢!!

最佳答案

来自Scott Gu's blog关于Many-valued Associations :

Many-to-Many Associations The association between Category and Item is a many-to-many association, as can be seen in the above class diagram. a many-to-many association mapping hides the intermediate association table from the application, so you don’t end up with an unwanted entity in your domain model. That said, In a real system, you may not have a many-to-many association since my experience is that there is almost always other information that must be attached to each link between associated instances (such as the date and time when an item was added to a category) and that the best way to represent this information is via an intermediate association class (In EF, you can map the association class as an entity and map two one-to-many associations for either side.).

In a many-to-many relationship, the join table (or link table, as some developers call it) has two columns: the foreign keys of the Category and Item tables. The primary key is a composite of both columns. In EF Code First, many-to-many associations mappings can be customized with a fluent API code like this:

    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());
  }

祝你好运,希望这有帮助!

关于c# - Entity Framework 代码优先 : Custom Mapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7026342/

相关文章:

c# - 有什么好的例子或框架可以教我n层开发吗?

c# - 包含循环,如果引用跟踪被禁用,则无法序列化,json.net 和 webapi

caching - EF 4.0模型缓存数据,并且不检测修改数据

domain-driven-design - Entity framework 4.0 + POCO + WCF 在DDD中的位置 "world"

C#/new关键字/类成员引用

c# - 过滤数据时简化linq

c# - 有趣的Linq to SQL通用基类行为

c# - 在 App.config 中设置 WPF 程序的文化

c# - .net Entity Framework 与 oracle 11g

entity-framework - 属性 'Id'是对象关键信息的一部分,不可修改