此代码不起作用。怎么了? OnModelCreating 不会影响任何结果?因为我在我的数据库中看不到“ProductCategories”表。
public class GoldContext : DbContext
{
public virtual DbSet<Prouct> Products { get; set; }
public virtual DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//HACK:4.1 modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
modelBuilder.Entity<Product>()
.HasMany<Category>(m => m.Categories)
.WithMany().Map(m =>
m.MapLeftKey("ProductId")
.MapRightKey("CategoryId")
.ToTable("ProductCategories"));
base.OnModelCreating(modelBuilder);
}
}
//product and category classes look like this.
public class Product
{
[Key]
public int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
提前致谢。
最佳答案
这是我在控制台应用程序中尝试过的并且按预期工作:
namespace Q7122388
{
#region Imports
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
#endregion
public class Product
{
[Key]
public int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class DatabaseContext : DbContext
{
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasMany<Category>(m => m.Categories)
.WithMany().Map(m =>
m.MapLeftKey("ProductId")
.MapRightKey("CategoryId")
.ToTable("ProductCategories"));
base.OnModelCreating(modelBuilder);
}
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseAlways<DatabaseContext>());
using (var context = new DatabaseContext())
context.Database.Initialize(true);
}
}
}
关于entity-framework - CTP5 与 4.1 EF 版的多对多关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7122388/