c# - EF5 代码优先 - 具有额外字段的多对多

标签 c# entity-framework ef-code-first entity-framework-5

我首先尝试将 awsome EF5 与代码一起使用 - 我需要在其中创建一个包含额外字段的多对多表。

我有一个产品表、订单表,并且需要一个包含“尺寸”字段的订单中的产品表。

我所做的是创建一个新类“ProductOrder”,作为它们之间的连接表,并进行引用。

它在创建新订单时有效,但在获取订单时无效 - 它无法获取连接的订单(插入后存在于数据库中)。

想法为什么? :)

我的类(class)是:

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

最佳答案

您的导航属性需要是虚拟的

关于c# - EF5 代码优先 - 具有额外字段的多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804701/

相关文章:

c# - C# 中的 Lambda 示例

c# - 只写属性,有什么意义?

entity-framework - Entity Framework 数据库开发入门(代码优先)

entity-framework - EF Core 中具有复合键的外键

c# - 如何将 C# 中的图像调整为特定的硬盘大小?

entity-framework - 可怕的 "parameter was not bound in the specified LINQ to Entities query expression"异常

c# - Entity Framework Core 中带有过滤器的复杂查询

c# - EF 的 DatabaseGeneratedOption.Identity 属性不适用于 ulong 类型

asp.net-mvc - 具有软删除功能的通用存储库

c# - JWT WriterToken 函数抛出 IDX10653 错误