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

时间:2018-02-17 20:14:58

标签: c# entity-framework asp.net-identity ef-code-first-mapping

我使用ASP.NET Identity 2.0和Entity Framework以及Code First方法。当我创建ApplicationUserManager的实例并调用CreateAsync方法时,如果我的用户和#39;属性都是原始类型:

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

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

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

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?)

我想要做的就是在User表中为此行设置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());
}

1 个答案:

答案 0 :(得分:1)

听起来好像_userStatusRepository和_userManager正在使用单独的DBContext实例。

如果您的代码使用相同的上下文并在此处{@ 3}}进行了有帮助的解释,那么您的代码应该按预期工作。

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