0

我正在使用 ASP.NET Identity 2.0 和 Entity Framework 以及 Code First 方法。当我创建一个实例ApplicationUserManager并调用该CreateAsync方法时,如果我的用户的属性都是原始类型,那么一切都很好:

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

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

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

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

我要做的就是在我的用户表中为这一行设置 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());
}
4

1 回答 1

1

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

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

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

于 2018-02-19T13:47:42.923 回答