Search code examples
c#entity-frameworkentity-framework-4entity-framework-4.1entity-relationship

Entity Framework Code First: Custom Mapping


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

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!!


Solution

  • 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!