使用 ApplicationUserManager.CreateAsync 创建用户并设置导航属性

Create user and set navigation properties using ApplicationUserManager.CreateAsync

我正在使用 ASP.NET Identity 2.0 和 Entity Framework 代码优先方法。当我创建 ApplicationUserManager 的实例并调用 CreateAsync 方法时,如果我的用户属性都是原始类型,一切都很好:

User user = new User
{
    UserName = _userManager.GetValidUserName(input.FullName),
    FullName = input.FullName,
    Email = input.EmailAddress
};

var result = await _userManager.CreateAsync(user); // OK

但是,如果我有一个实体类型的 属性 然后尝试设置它,代码会尝试 在相关的 table 中创建一个新行该实体 并因此崩溃(因为行是唯一的):

User user = new User
{
    UserName = _userManager.GetValidUserName(input.FullName),
    FullName = input.FullName,
    Email = input.EmailAddress,
    Status = _userStatusRepository.Find(us => us.Name == UserStatus.USER_STATUS_MIGRATED) // this line causes the problem
};

var result = await _userManager.CreateAsync(user); // crashes whilst trying to create a new row for USER_STATUS_MIGRATED in the DB (why would it do that?)

我想要做的就是在我的用户 table 中为此行设置 UserStatusId 列;但我不知道该怎么做。相关代码如下所示:

public class User : IdentityUser<int, UserLogin, UserRole, UserClaim>
{
    public string FullName { get; set; }
    public virtual UserStatus Status { get; set; } // custom DB entity
    // other properties inherited from IdentityUser; e.g., UserName, Email etc.
}

public class UserStatus : Entity
{
    public static readonly string USER_STATUS_MIGRATED = "Migrated";

    public string Name { get; set; }
    public string Description { get; set; }
}

[Serializable]
public abstract class Entity
{
    public virtual int Id { get; set; }
}

public class UserEntityConfiguration : EntityTypeConfiguration<User>
{
    public UserEntityConfiguration()
    {
        ToTable("User");
        HasRequired(u => u.Status);
        Property(u => u.FullName).IsRequired();
        Ignore(u => u.PhoneNumberConfirmed);
    }
}

public class UserStatusEntityConfiguration : EntityTypeConfiguration<UserStatus>
{
    public UserStatusEntityConfiguration()
    {
        Property(e => e.Name).IsRequired().HasColumnAnnotation(IndexAnnotation.AnnotationName,
            new IndexAnnotation(new IndexAttribute("IX_Name") { IsUnique = true })
            );
        Property(e => e.Description).IsRequired();
    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.Configurations.Add(new UserEntityConfiguration());
    modelBuilder.Configurations.Add(new UserStatusEntityConfiguration());
}

我觉得 _userStatusRepository 和 _userManager 正在使用不同的 DBContext 实例。

如果两者使用相同的上下文并且在此处进行了有益的解释,您的代码应该会按预期工作 https://msdn.microsoft.com/en-us/magazine/dn166926.aspx

检查您创建 DBContext 实例的方式和位置,以确保两个存储库具有相同的实例。如果您正在使用依赖注入,通常对 DBContext 使用每个请求的生命周期范围,因此所有存储库都将使用相同的上下文实例,只要是同一请求的所有部分。