Entity Framework 核心拥有的类型值对象在与 IdentityUser 一起使用时抛出需要定义主键的错误。为什么?

Entity Framework Core Owned Type Value Object throws required Primary Key to be defined error when used with IdentityUser. Why?

我正在使用 EF Core 2.2。我的应用程序中有两个上下文。一个是 AppIdentityDbContext 用于与身份相关的作品,另一个是 AppContext 用于与应用程序相关的作品。

我有一个身份用户 class - ApplicationUser - 它与来自 AppContextProfile 实体有关系,而 Profile 实体又拥有一个值对象 ProfileContact

代码如下:

应用程序用户

public class ApplicationUser : IdentityUser<Guid>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Designation { get; set; }

    public Guid ProfileId { get; set; }
    public Profile Profile { get; set; }
}

简介

public class Profile : BaseEntity<Guid>, IAggregateRoot
{
    private Profile()
    {
        // required by EF
    }

    public Profile(string brandName, ProfileContact profileContact)
    {
        BrandName = brandName;
        ProfileContact = profileContact;
    }

    public string BrandName { get; set; }

    public ProfileContact ProfileContact { get; private set; }
}

个人资料联系人

public class ProfileContact // ValueObject
{
    private ProfileContact()
    {
        // required by EF
    }

    public ProfileContact(string email, string phone, string mobile)
    {
        Email = email;
        Phone = phone;
        Mobile = mobile;
    }

    public string Email { get; private set; }
    public string Phone { get; private set; }
    public string Mobile { get; private set; }
}

IAggregateRoot

IAggregateRoot 是一个空接口,用于限制实体在我的项目中使用通用存储库。

public interface IAggregateRoot
{
}

AppContext

这是AppContext中的'Profile'实体配置。

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Profile>(ConfigureProfile);
}

private void ConfigureProfile(EntityTypeBuilder<Profile> builder)
{
    builder.Property(p => p.BrandName)
        .IsRequired()
        .HasMaxLength(50);

    builder.OwnsOne(p => p.ProfileContact);
}

我已将 ProfileContact 配置为由 Profile 个实体拥有。

现在每当用户登录时,我都会收到此错误:

这是我的登录Post方法。我正在使用 Asp.Net Core Identity 脚手架模板。

登录 - OnPostAsync

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
   returnUrl = returnUrl ?? Url.Content("~/");

   if (ModelState.IsValid)
   {
       // This doesn't count login failures towards account lockout
       // To enable password failures to trigger account lockout, set lockoutOnFailure: true
       var result = await _signInManager.PasswordSignInAsync(Input.MobileNumber, Input.Password, Input.RememberMe, lockoutOnFailure: true);
       if (result.Succeeded)
       {
         ....

    // If we got this far, something failed, redisplay form
    return Page();
}

值object/owned类型是否需要定义键?我对 OwnedTypes 的阅读和理解是它们属于同一个 table 但可以用作对象。我做错了什么吗?或者我需要将 Id 属性 添加到 ProfileContact。如果是,为什么?请协助。

我认为如果您有两个单独的上下文,就会发生此问题。一个用于应用程序,另一个用于具有自定义 ASP.NET 身份模型的 Asp.Net 身份。在这两种情况下实体之间的关系也是如此。

在这种情况下,在 contextOnModelCreating(ModelBuilder builder) 中添加 base.OnModelCreating(builder) 即可解决问题。

感谢Gert Arnold的指导和教导。致谢。