我正在尝试首先使用awsome EF5代码 - 我需要在其中创建具有额外字段的多对多表。
我有一个产品表,订单表,需要一个产品表,其中包含“大小”字段的订单。
我所做的是创建了一个新的“ProductOrder”类,它是它们之间的连接表,并作了参考。
它在创建新订单时起作用,但在获取订单时不起作用 - 它不会获得连接订单(插入后在DB中存在)。
想法为什么? :)
我的课程是:
public class Order { public int ID { get; set; } ... public ICollection<ProductOrder> Products { get; set; } public Order() { Products = new HashSet<ProductOrder>(); } } public class Product { public int ID { get; set; } public ICollection<ProductOrder> Orders { get; set; } } public class ProductOrder { public int ID { get; set; } public int ProductID { get; set; } public int OrderID { get; set; } public int Size { get; set; } [ForeignKey("OrderID")] public Order order { get; set; } [ForeignKey("ProductID")] public Product product { get; set; } }并在onModelCreating
modelBuilder.Entity<Order>() .HasMany(p => p.Products) .WithRequired(o => o.order) .HasForeignKey(o => o.OrderID); modelBuilder.Entity<Product>() .HasMany(o => o.Orders) .WithRequired(p => p.product) .HasForeignKey(p => p.ProductID);I'm trying to use the awsome EF5 with code first - where I need to make a many-to-many table with extra fields.
I've got a products table, orders table and need a table of products that are in orders with a "size" field.
What I've done is created a new class of "ProductOrder" that is the connection table between them, and made a reference.
It WORKS when creating a new order, but is not working when fetching an order - it doesn't get the connected orders (that are present in the DB after the insertion).
Ideas why? :)
My Classes are:
public class Order { public int ID { get; set; } ... public ICollection<ProductOrder> Products { get; set; } public Order() { Products = new HashSet<ProductOrder>(); } } public class Product { public int ID { get; set; } public ICollection<ProductOrder> Orders { get; set; } } public class ProductOrder { public int ID { get; set; } public int ProductID { get; set; } public int OrderID { get; set; } public int Size { get; set; } [ForeignKey("OrderID")] public Order order { get; set; } [ForeignKey("ProductID")] public Product product { get; set; } }and in onModelCreating
modelBuilder.Entity<Order>() .HasMany(p => p.Products) .WithRequired(o => o.order) .HasForeignKey(o => o.OrderID); modelBuilder.Entity<Product>() .HasMany(o => o.Orders) .WithRequired(p => p.product) .HasForeignKey(p => p.ProductID);最满意答案
您的导航属性需要是虚拟的
Your navigational properties need to be virtual
更多推荐
发布评论