简体   繁体   English

C# - 实体框架核心 - 多对多关系错误

[英]C# - Entity Framework Core - Many to Many relation error

After I added the base class BaseModel for each entity, I get the next error for each many-to-many entities relation (in this case it's OrderProduct):在为每个实体添加基本 class BaseModel之后,我得到每个多对多实体关系的下一个错误(在本例中是 OrderProduct):

System.InvalidOperationException: A key cannot be configured on 'OrderProduct' because it is a derived type. System.InvalidOperationException:无法在“OrderProduct”上配置密钥,因为它是派生类型。 The key must be configured on the root type 'BaseModel'.必须在根类型“BaseModel”上配置密钥。 If you did not intend for 'BaseModel' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.如果您不打算将“BaseModel”包含在 model 中,请确保它不包含在您的上下文的 DbSet 属性中、在对 ModelBuilder 的配置调用中引用或从包含的类型的导航属性中引用在 model 中。

Did I miss something while adding the base class?添加基础 class 时我错过了什么吗?

Here are the entities:以下是实体:

public class BaseModel
{
    public DateTime? CreatedAt { get; set; }
    public User CreatedBy { get; set; }
    public int? CreatedById { get; set; }
}
public class OrderProduct : BaseModel
{
    public int OrderId { get; set; }
    public Order Order { get; set; }

    public int ProductId { get; set; }
    public Product Product { get; set; }
}
public class Order : BaseModel
{
    /*...*/ 
    public IList<OrderProduct> OrderProducts { get; set; }
}
public class Product : BaseModel
{
    /*...*/
    public IList<OrderProduct> OrderProducts { get; set; }
}

And here is my entities configuration in the context class:这是我在 class 上下文中的实体配置:

protected override void OnModelCreating(ModelBuilder builder)
{
    /*...*/
    builder.Entity<OrderProduct>()
        .HasKey(u => new { u.OrderId, u.ProductId });

    builder.Entity<OrderProduct>()
        .HasOne(u => u.Order)
        .WithMany(u => u.OrderProducts)
        .HasForeignKey(u => u.OrderId);

    builder.Entity<OrderProduct>()
        .HasOne(u => u.Product)
        .WithMany(u => u.OrderProducts)
        .HasForeignKey(u => u.ProductId);
    /*...*/
}

According to the error, there can be no key in OrderProduct because it inherits BaseModel and the key should be in the base class ( BaseModel ).根据错误, OrderProduct中可能没有键,因为它继承BaseModel并且键应该在基础 class ( BaseModel )中。 If you want it to be in OrderProduct , exclude BaseModel from the model by NOT having it in any DbSet and OnModelCreating (so that you do NOT invoke .Entity<BaseModel> or similar.如果您希望它在OrderProduct中,请从 model 中排除BaseModel ,方法是不要将它放在任何DbSetOnModelCreating (这样您就不会调用.Entity<BaseModel>或类似的东西。

In your case I would simply have a key (ID) field in BaseModel .在您的情况下,我只需在BaseModel中有一个键(ID)字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM