dotnet / dotnet/efcore

Throws an exception :A key cannot be configured on 'USER' because it is a derived type. while calling EntityBase as one of the [Notmapped] properties in EntityBase

Open
#29,890 6 comments 0 reactions 0 assignees View on GitHub
area-model-building customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

## in dotnet 6, i have three Entities USER, DEPARTMENT and TRANSPORTATION ,all are derived from a class EntityBase.
a. USER has one to many relation with DEPARTMENT aswell as TRANSPORTATION .
b. DEPARTMENT has one to many Relationship with TRANSPORTATION.
c. used EntityFramework in memory .

The application is running perfectly untill i use a Property ' public EntityBase Test2 { get; set; } ' in the class EntityBase . [NotMapped] has been assigned to it and ignored this property in BaseMapping aswell.
while running the console before reaching the method 'OnModelCreating' the exception has been thrown.

May i know what mistake i have attempted. kindly support me to reach the solution.

```C#
**// main class**
internal class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello, World!");

var context = new SampleModel();

try
{
var test = await context.Database.CanConnectAsync();
Console.WriteLine("Success!");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

Console.ReadLine();
}
}

**//Sample model**
public class SampleModel : DbContext
{

public DbSet USER { get; set; }
public DbSet DEPARTMENT { get; set; }
public DbSet TRANSPORTATION { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("TestDb");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.ApplyConfiguration(new UserMapping());
modelBuilder.ApplyConfiguration(new DepartmentMapping());
modelBuilder.ApplyConfiguration(new TransportationMapping());

}
}
**// EnitityBase**
public class EntityBase : IComparable
{
#region Base Properties

public DateTime CREATEDON { get; set; }

**[NotMapped]
public EntityBase Test2 { get; set; }**

public int CompareTo(EntityBase other)
{
int result = 0;
int counter = 0;

return result;
}

#endregion Clone
}

**// USER**
public partial class USER : EntityBase
{
public USER()
{
}

[Key]
public int USER_ID { get; set; }

public Nullable DEPARTMENT_ID { get; set; }
public Nullable TRANSPORTATION_ID { get; set; }

public virtual DEPARTMENT DEPARTMENT { get; set; }

public virtual TRANSPORTATION TRANSPORTATION { get; set; }
}

**//DEPARTMENT**
public partial class DEPARTMENT : EntityBase
{
public DEPARTMENT()
{

}

[Key]
public int DEPARTMENT_ID { get; set; }

public int TRANSPORT_ID { get; set; }

public virtual TRANSPORTATION TRANSPORTATION { get; set; }

public virtual ICollection USERS { get; set; }


}
**//TRANSPORTATION**
public partial class TRANSPORTATION : EntityBase
{
public TRANSPORTATION()
{
}

[Key]
public int TRANSPORT_ID { get; set; }


}
// MAPPINGS
//BaseMapping
public abstract class BaseMapping : IEntityTypeConfiguration where T : EntityBase
{

public virtual void Configure(EntityTypeBuilder builder)
{
builder.Property(e => e.CREATEDON).IsRequired();
builder.Ignore(e => e.Test2);

}

}
//userMapping
public class UserMapping :BaseMapping
{
public override void Configure(EntityTypeBuilder builder)
{
base.Configure(builder);

//PrimaryKey
builder.HasKey(e => e.USER_ID);
builder.Property(e => e.USER_ID).ValueGeneratedOnAdd();

//////OneToMany
builder.HasOne(e => e.TRANSPORTATION).WithMany().HasForeignKey(e => e.TRANSPORTATION_ID);
builder.HasOne(e => e.DEPARTMENT).WithMany(e=>e.USERS).HasForeignKey(e => e.DEPARTMENT_ID);
}
}

//TRansportationMapping
internal class TransportationMapping : BaseMapping
{
public override void Configure(EntityTypeBuilder builder)
{
base.Configure(builder);
//PrimaryKey
builder.HasKey(e => e.TRANSPORT_ID);
builder.Property(e => e.TRANSPORT_ID).ValueGeneratedOnAdd();

}
}

//Department Mapping
internal class DepartmentMapping : BaseMapping
{
public override void Configure(EntityTypeBuilder builder)
{
base.Configure(builder);
//PrimaryKey
builder.HasKey(e => e.DEPARTMENT_ID);
builder.Property(e => e.DEPARTMENT_ID).ValueGeneratedOnAdd();

builder.HasOne(e => e.TRANSPORTATION).WithMany().HasForeignKey(e => e.TRANSPORT_ID);
}
}
```

```
Console.WriteLine("Hello, World!");Hello, World!
System.InvalidOperationException: A key cannot be configured on 'USER' because it is a derived type. The key must be configured on the root type 'EntityBase'. If you did not intend for 'EntityBase' to be included in the model, ensure that it is not referenced by a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation on a type that is included in the model.
at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.AddKey(IReadOnlyList`1 properties, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasKeyInternal(IReadOnlyList`1 properties, Nullable`1 configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.PrimaryKey(IReadOnlyList`1 properties, ConfigurationSource configurationSource)
at Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasKey(Expression`1 keyExpression)
at SampleEFCore.Mappings.UserMapping.Configure(EntityTypeBuilder`1 builder)
at Microsoft.EntityFrameworkCore.ModelBuilder.ApplyConfiguration[TEntity](IEntityTypeConfiguration`1 configuration)
at SampleEFCore.SampleModel.OnModelCreating(ModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, ModelCreationDependencies modelCreationDependencies, Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure.get_Instance()
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.CanConnectAsync(CancellationToken cancellationToken)
at SampleEFCore.Program.Main(String[] **args)**
```

###Exception

System.InvalidOperationException: "A key cannot be configured on 'USER' because it is a derived type. The key must be configured on the root type 'EntityBase'. If you did not intend for 'EntityBase' to be included in the model, ensure that it is not referenced by a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation on a type that is included in the model."

EF Core version: 6.0.12
Database provider: (e.g. Microsoft.EntityFramework In Memory)
Target framework: (e.g. .NET 6.0.12)
Operating system: Windows
IDE: (e.g. Visual Studio 2022 17.4)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.