我正在使用 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());
}