Sunday, January 16, 2011

Many-to-Many table mapping in EF CTP5

Was just reading that the method of many-to-many mapping is different in CTP5.  Here’s the method:

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Store> SoldAt { get; set; }
}

public class Store
{
public int Id { get; set; }
public string StoreName { get; set; }
public ICollection<Product> Products { get; set; }
}

public class MyContext : DbContext
{
public DbSet<Product> Products { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<Product>()
.HasMany(p => p.SoldAt)
.WithMany(s => s.Products)
.Map(mc => {
mc.ToTable("ProductsAtStores");
mc.MapLeftKey(p => p.Id, "ProductId");
mc.MapRightKey(s => s.Id, "StoreId");
});
}

No comments: