Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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 #29890

Open
gatlasairam opened this issue Dec 19, 2022 · 5 comments

Comments

@gatlasairam
Copy link

gatlasairam commented Dec 19, 2022

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.

**// 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> USER { get; set; }
        public DbSet<DEPARTMENT> DEPARTMENT { get; set; }
        public DbSet<TRANSPORTATION> 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<EntityBase>
    {
        #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<int> DEPARTMENT_ID { get; set; }
        public Nullable<int> 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<USER> USERS { get; set; }

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

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

       
    }
// MAPPINGS
//BaseMapping
 public abstract class BaseMapping<T> : IEntityTypeConfiguration<T>  where T : EntityBase
    {
       
        public virtual void Configure(EntityTypeBuilder<T> builder) 
        {
            builder.Property(e => e.CREATEDON).IsRequired();
            builder.Ignore(e => e.Test2);
            
        }

    }
//userMapping
public class UserMapping :BaseMapping<USER>
    {
        public override void Configure(EntityTypeBuilder<USER> 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<TRANSPORTATION>
    {
        public override void Configure(EntityTypeBuilder<TRANSPORTATION> builder)
        {
            base.Configure(builder);
            //PrimaryKey
            builder.HasKey(e => e.TRANSPORT_ID);
            builder.Property(e => e.TRANSPORT_ID).ValueGeneratedOnAdd();

        }
    }

//Department Mapping
 internal class DepartmentMapping : BaseMapping<DEPARTMENT>
    {
        public override void Configure(EntityTypeBuilder<DEPARTMENT> 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.<RealizeService>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<System.IServiceProvider>.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)

@gatlasairam gatlasairam changed the title Throws an exception :A key cannot be configured on 'USER' because it is a derived type. while calling EntityBase as property in BaseMapping 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 Dec 20, 2022
@gatlasairam gatlasairam changed the title 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 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 Dec 20, 2022
@ajcvickers
Copy link
Member

@gatlasairam Please post the code for UserMapping, DepartmentMapping, and TransportationMapping.

@gatlasairam
Copy link
Author

@gatlasairam Please post the code for UserMapping, DepartmentMapping, and TransportationMapping.

Appended in the above code.

@ajcvickers
Copy link
Member

@gatlasairam Explicitly ignore EntityBase so that it is not mapped as an entity type. For example:

modelBuilder.Ignore<EntityBase>();
modelBuilder.ApplyConfiguration(new UserMapping());
modelBuilder.ApplyConfiguration(new DepartmentMapping());
modelBuilder.ApplyConfiguration(new TransportationMapping());

Note for triage: a navigation from an unmapped base type to an unmapped base type causes that base type to be mapped even when the navigation is ignored with [NotMapped] when there are certain relationships between the types. Minimal repro:

public class SampleModel : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Transportation> Transportation { get; set; }

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

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

public class User : EntityBase
{
    public int Id { get; set; }

    public Department Department { get; set; }
    public Transportation Transportation { get; set; }
}

public class Department : EntityBase
{
    public int Id { get; set; }
    public Transportation Transportation { get; set; }
    public ICollection<User> Users { get; set; }
}

public class Transportation : EntityBase
{
    public int Id { get; set; }
}

@gatlasairam
Copy link
Author

@ajcvickers Thank you so much, it is working :)

@ajcvickers
Copy link
Member

Note from triage: should be fixed by layering.

@ajcvickers ajcvickers added this to the Backlog milestone Dec 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants