开发者

Entity Framework Code First: Custom Mapping

p开发者_开发问答ublic class User
{
   public int Id {get;set;}

   public string Name {get;set}

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

My Model looks like above, Entity framework automatically creates A table and UserUser with rows User_ID and User_ID1 in DB to map this model. I want to map that table and rows myself.

How can i do that, Thanx!!


From Scott Gu's blog about 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");
            });
    } }

Register this configuration in your DbContext's (you using the DbContext api right?) like this:

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

    modelBuilder.Configurations.Add(new ItemConfiguration());
  }

Good luck, hope this help!


To map an entity to itself, you would do something like this

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

    base.OnModelCreating(modelBuilder);
}

its hard to tell without seeing your database model though, and how you actually relate the followers to the user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜