EF5代码优先

编程入门 行业动态 更新时间:2024-10-28 18:30:51
EF5代码优先 - 多对多具有额外字段(EF5 Code first - Many to Many with extra fields)

我正在尝试首先使用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

更多推荐

本文发布于:2023-07-27 08:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1288010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!