vlad-pavluk
vlad-pavluk

Reputation: 23

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

System.InvalidOperationException : A key cannot be configured on 'OrderProduct' because it is a derived type. The key must be configured on the root type '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.

Did I miss something while adding the base 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:

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);
    /*...*/
}

Upvotes: 2

Views: 168

Answers (1)

misticos
misticos

Reputation: 797

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

In your case I would simply have a key (ID) field in BaseModel.

Upvotes: 1

Related Questions