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

Inheritance does not discover Id as PK by conventions #7885

Closed
ShenZZ opened this issue Mar 15, 2017 · 11 comments
Closed

Inheritance does not discover Id as PK by conventions #7885

ShenZZ opened this issue Mar 15, 2017 · 11 comments
Assignees
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug
Milestone

Comments

@ShenZZ
Copy link

ShenZZ commented Mar 15, 2017

TPH add-migration exception

Model:

   public class AppUser
    {
        public string Id { get; set; }
    }
    public class Employee : AppUser{}

Exception message:
System.InvalidOperationException: The entity type 'AppUser' requires a primary key to be defined.
Stack trace:
System.InvalidOperationException: The entity type 'AppUser' requires a primary key to be defined.
at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message)
at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model)
at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_01.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

Steps to reproduce

Include a complete code listing (or project/solution) that we can run to reproduce the issue.

Partial code listings, or multiple fragments of code, will slow down our response or cause us to push the issue back to you to provide code to repoduce the issue.

<code listing>

Further technical details

EF Core version: 1.1.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system:
IDE: Visual Studio 2015

@ShenZZ
Copy link
Author

ShenZZ commented Mar 15, 2017

if use the Fluent API set the key, migration is ok.
builder.Entity().HasKey(a => a.Id);

or property is "int Id" migration is ok.

@ajcvickers
Copy link
Contributor

@ShenZZ I have not been able to repro this with just the information provided. Here is my attempt at a simple console app to show the issue. Can you provide a full project or code listing that demonstrates what you are seeing, perhaps using the listing below as a starting point?

public class Program
{
    public static void Main()
    {
        using (var context = new TestContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Add(new AppUser { Id = "1" });
            context.Add(new Employee { Id = "2" });

            context.SaveChanges();
        }
    }
}

public class TestContext : DbContext
{
    public DbSet<AppUser> AppUser { get; set; }
    public DbSet<Employee> Employee { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(
            @"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;ConnectRetryCount=0");
    }
}

public class AppUser
{
    public string Id { get; set; }
}

public class Employee : AppUser
{
}

@ShenZZ
Copy link
Author

ShenZZ commented Mar 16, 2017

public class TestContext : DbContext
{
//public DbSet AppUser { get; set; }
public DbSet User { get; set; }
public DbSet Employee { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(
        @"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;ConnectRetryCount=0");
}

}

this will throw exception ...

@ajcvickers
Copy link
Contributor

@ShenZZ How is the class User defined?

@ShenZZ
Copy link
Author

ShenZZ commented Mar 23, 2017

public class Program
    {
        public static void Main()
        {
            using (var context = new TestContext())
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                context.Add(new AppUser { Id = "1" });
                context.Add(new Employee { Id = "2" });

                context.SaveChanges();
            }
        }
    }

    public class TestContext : DbContext
    {
        //public DbSet<AppUser> AppUser { get; set; }
        public DbSet<AppUser> User { get; set; }
        public DbSet<Employee> Employee { get; set; }

        public TestContext(DbContextOptions<TestContext> options)
            : base(options)
        {
        }
        public TestContext()
            : base()
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(
                @"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;ConnectRetryCount=0");
        }
    }

    public class AppUser
    {
        public string Id { get; set; }
    }

    public class Employee : AppUser
    {
    }

@ajcvickers
Copy link
Contributor

@ShenZZ Thanks for the repro!

Note for triage: this code works if the AppUser DbSet property name is "AppUser":

public DbSet<AppUser> AppUser { get; set; }

but fails if the property name is "User"

public DbSet<AppUser> User { get; set; }

@ShenZZ ShenZZ closed this as completed Mar 24, 2017
@divega
Copy link
Contributor

divega commented May 8, 2017

Reopening since the behavior described still seems to be a bug worth discussing in triage.

@divega divega reopened this May 8, 2017
@smitpatel smitpatel self-assigned this May 8, 2017
@smitpatel
Copy link
Contributor

@divega - This is bug. I was investigating this as I was surprised to see how come name of db set would ever affect KeyDiscoveryConvention. Based on ordering of discovery of Employee & AppUser, only one ordering works fine. It should be same in both cases.

@smitpatel smitpatel changed the title TPH add-migration exception Detaching Keys sets IsNullable true explicitly for string property May 8, 2017
@smitpatel smitpatel changed the title Detaching Keys sets IsNullable true explicitly for string property Inheritance does not discover Id as PK by conventions May 8, 2017
@smitpatel smitpatel added this to the 2.0.0 milestone May 8, 2017
@smitpatel smitpatel added the closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. label May 8, 2017
@divega
Copy link
Contributor

divega commented May 9, 2017

Thanks @smitpatel.

@bricelam bricelam modified the milestones: 2.0.0, 2.0.0-preview2 May 16, 2017
@silencieuxle
Copy link

silencieuxle commented Oct 22, 2017

Still not work for me?

public abstract class BaseEntity<TPrimaryKey>
{
        [Key]
        protected TPrimaryKey Id { get; set; }

        public DateTime DateCreated { get; set; }

        public DateTime DateModified { get; set; }
}
public abstract class Entity : BaseEntity<int>
{
        
}
public class Customer : Entity
{
        public string FirstName { get; set; }

        public string LastName { get; set; }
}

The entity type 'Customer' requires a primary key to be defined.

@smitpatel
Copy link
Contributor

@silencieuxle - Your issue is much different from this issue, please file a new issue with repro code and version of EF Core you are using.

@ajcvickers ajcvickers modified the milestones: 2.0.0-preview2, 2.0.0 Oct 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug
Projects
None yet
Development

No branches or pull requests

6 participants