使用applicationusermanager.createasync创建用户并设置导航属性



我使用的是ASP.NET Identity 2.0和实体框架,并使用代码第一次方法。当我创建ApplicationUserManager的实例并调用CreateAsync方法时,如果我的用户的属性都是原始类型,则一切都很好:

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

我要做的就是在用户表中为此行设置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的每个请求寿命范围,因此,只要在同一请求的所有部分中,所有存储库都将使用上下文的相同实例。

相关内容

  • 没有找到相关文章

最新更新