将ASP.NET标识集成到现有数据库

时间:2014-06-07 17:47:06

标签: c# asp.net asp.net-mvc entity-framework asp.net-identity

我对所有这些实体框架的内容都很陌生,所以请原谅我。

我试图将ASP.NET Identity集成到我的项目中。我已经有了一个现有的数据库,已映射并准备就绪,而且我正在使用Code First进行自动迁移。我尝试做的是将Identity仅存储用户名,密码和其他一些字段,其余信息需要存储在另一个名为Contact的表中,所以我需要从我的身份到1:1的连接我的那张桌子。

到目前为止我所尝试的是在一个环境中合并,所以我得到的是:

public partial class pmdb02Context : IdentityDbContext
{
    static pmdb02Context()
    {
        Database.SetInitializer<pmdb02Context>(null);
    }

    public pmdb02Context()
        : base("pmdb02Context")
    {
    }

    --- Lots of DbSets ---

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        --- Lots of Mappings ---

        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
        modelBuilder.Entity<ApplicationUser>().ToTable("IdentityUsers", "dbo");    
    }
}

当我到达时:

var result = await UserManager.CreateAsync(user, model.ContactData.Password);

我收到了这个:

IdentityUser_Logins_Target: : Multiplicity is not valid in Role 'IdentityUser_Logins_Target' in relationship 'IdentityUser_Logins'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

我的ApplicationUser类如下所示:

public class ApplicationUser : IdentityUser
{
    public int ContactId { get; set; }
    public bool? IsCurrent { get; set; }

    public virtual Contact Contact { get; set; } 
}

所以,我需要一个与联系人的关系。 我想,我的问题在于我试图让这些东西一起工作,我昨天和今天一直试图这样做。

我非常感谢任何帮助。 谢谢!

2 个答案:

答案 0 :(得分:0)

在创建用户时,您还必须创建联系人。因此,如果稍后将创建联系人 将用户和联系人之间的关系更改为1到(1..0)。

public class ApplicationUser : IdentityUser
{
    public bool? IsCurrent { get; set; }
    public virtual Contact Contact { get; set; } 
}

public class Contact
{
    .
    .
    .
    public virtual ApplicationUser User { get; set; } 
}

modelBuilder.Entity<Contact>().HasRequired(c => c.User).WithOptional(u => u.Contact);

编辑: 因此,关系为1到(1..0),用户的id将用于联系人ID,您需要选择用户并将其分配给联系人的用户属性;

var user db.users.Single(u => u.Id == id);
contact.User = user;

答案 1 :(得分:0)

昨天终于解决了我的问题。 事实证明我的问题的主要来源是这一行:

Database.SetInitializer<pmdb02Context>(null);

当我将其更改为:

Database.SetInitializer<pmdb02Context>(new MigrateDatabaseToLatestVersion<pmdb02Context, Configuration>());

身份终于按照惯例工作,我只像往常一样将关系添加到联系人。