EF Core 2.0.1 Using IdentityUser as navigation property

asp.net asp.net-mvc entity-framework entity-framework-core

Question

When I try to register a user or create a migration I get the following error:

"A key cannot be configured on 'ApplicationUser' because it is a derived type. The key must be configured on the root type 'IdentityUser'. If you did not intend for 'IdentityUser' 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."

I have a BaseEntity that everything derives from like so:

public class BaseEntity
    {
        public int Id { get; set; }

        [Required]
        public DateTime DateCreated { get; set; }

        [Required]
        public DateTime DateModified { get; set; }

        [Required]
        public string CreatedById { get; set; }

        [Required]
        public string ModifiedById { get; set; }

        public virtual IdentityUser CreatedBy { get; set; }
        public virtual IdentityUser ModifiedBy { get; set; }
    }

public class FilePath : BaseEntity, IAuditable
    {
        [StringLength(255)]
        public string FileName { get; set; }
        public FileType FileType { get; set; }
    }

Is there a new rule or update that says you can't use IdentityUser as a navigation property? Google hasn't brought much useful information.

The entire solution is here if required.

Update: After upgrading to 2.0.1 preview, the errors are a little more helpful:

The best match for foreign key properties {'Id' : string} are incompatible with the principal key {'Id' : int}.

1
3
3/3/2018 9:14:48 PM

Popular Answer

I faced the same issue. You need to replace all places in code where you use BaseEntity to FilePath.

Example: I had inheritance like:

public class ApplicationUser : IdentityUser
    {

    }

and I changed ApplicationDbContext like:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }


        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }

but I got the same Exception.

After I replaced IdentityUser to ApplicationUser in code the Error has gone. I reckon you should work with BaseEntity through FilePath in Data Acces Layer.

1
9/24/2019 2:19:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow