Add-Migration error with EF Core Owned type

c# entity-framework-core


I have two "owned" types referenced from ApplicationUser (which inherits from IdentityUser):

using System;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace OwnedEntityTest.Data
    public class ApplicationUser : IdentityUser
        public PersonalName Name { get; set; }
        public ValidationToken ValidationToken { get; set; }

    public class PersonalName
        public string FirstName { get; set; }
        public string LastName { get; set; }

    public class ValidationToken
        public int ValidationCode { get; set; }
        public DateTime ExperiationDateUTC { get; set; }

When I add a new migration, the scaffolder complains:

Cannot use table 'IdentityUser' for entity type 'ValidationToken' since it is being used for entity type 'PersonalName' and there is no relationship between their primary keys.

Is this just a bug, or am I doing something subtly wrong (or not understanding something about owned types)?

Yes, you can recreate this problem:

  1. Create a new project from the ASP.NET Core Web Application project template
  2. Select Web Application
  3. Click Change Authentication and select Individual user accounts
  4. In Package Manager Console, enter update-database to update the model snapshot.
  5. Add the above code to the project
  6. In ApplicationDbContext, add the reference to ApplicationUsers:
    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
  7. Add a new migration in Package Manager Console:
    add-migration m_001
  8. Ta dah... you should see the error message


Microsoft has confirmed that this is a bug.

1/23/2019 8:33:42 PM

Accepted Answer

In the mean time, you can use the fluent method to configure this.

  1. Remove the [Owned] attributes from the data model
  2. Configure the relationship by overriding the OnModelCreating method on your ApplicationDbContext

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        modelBuilder.Entity<ApplicationUser>(b =>
            b.OwnsOne(e => e.Name);
            b.OwnsOne(e => e.ValidationToken);
1/30/2019 1:41:58 AM

Related Questions


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