gpt4 book ai didi

asp.net-mvc - ASP.NET Identity 2.1 和 EF 6 - 应用程序用户与其他实体的关系

转载 作者:行者123 更新时间:2023-12-02 01:48:21 25 4
gpt4 key购买 nike

似乎无法找到这个问题的答案,尽管我正在做的事情对于大多数开发人员来说似乎是常见且重要的。在大多数具有用户帐户的系统中,用户表与数据库中的其他表相关联。这就是我想要的。我正在使用 MSSQL Express 2012 和 VS 2013。

我有一个类库,我在其中使用代码优先方法来生成表。我也将 IdentityModel 类从 MVC 项目移至该类库。一切都是单独工作的 - 我的表已生成并且工作正常,并且身份表是在我注册新用户时生成的。

但是,现在我需要一个实体/表以 1-1 关系与 ApplicationUser 绑定(bind),但像这样添加字段会阻止生成 Identity 表:

public class ApplicationUser : IdentityUser
{
//***custom field
public MyPortfolio Portfolio { get; set; }

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("name=MyDataModel", throwIfV1Schema: false)
{
}

public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

base.OnModelCreating(modelBuilder);

//sql output log
Database.Log = s => Debug.Write(s);
}
}

...“MyPortfolio”只是普通实体:

    public class MyPortfolio
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[StringLength(45, MinimumLength = 3)]
public string Name { get; set; }

public Boolean IsMaster { get; set; }

//public ApplicationUser User { get; set; } //threw exception!
}

我对身份了解不多,但读过迁移可能是答案。如果可能的话,我宁愿避免任何进一步的复杂性。这真的有必要吗?我正处于早期开发阶段,将会多次删除/重新创建表格。

更新1:

好的,我添加了如下所述的 adricadar 等所有内容。这就是发生的事情...

添加迁移时,我必须从包管理器控制台的“默认项目”下拉列表中选择我的类库。在执行 Enable-Migrations 时,出现以下错误:

More than one context type was found in the assembly 'MyProject.Data'. To enable migrations for 'MyProject.Models.ApplicationDbContext', use Enable-Migrations -ContextTypeName MyProject.Models.ApplicationDbContext. To enable migrations for 'MyProject.Data.MyDataModel', use Enable-Migrations -ContextTypeName MyProject.Data.MyDataModel.

...所以我做了以下操作:

Enable-Migrations -ContextTypeName MyProject.Models.ApplicationDbContext

...正如预期的那样,为 AspNetUser* 表创建了 Configuration 类和“InitialCreate”类。

然后我运行“Add-Migration UserPortofolioRelation”,它使用 Up() 和 Down() 生成 DbMigration 类。 Up 和 Down 都定义了我在 MyDataModel 中定义的所有表。我现在在 Up() 中看到了 MyPortfolio 和 AspNetUsers 之间的关系:

        CreateTable(
"dbo.MyPortfolio",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 45),
IsMaster = c.Boolean(nullable: false),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);

当我运行 Update-Database 时,出现以下错误:

Applying explicit migrations: [201504141316068_UserPortofolioRelation]. Applying explicit migration: 201504141316068_UserPortofolioRelation. System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'MyPortfolio' in the database.

我对迁移的了解程度就是这个基本教程:

https://msdn.microsoft.com/en-us/data/jj591621.aspx

这对我有用,并且在生成的迁移代码中仅定义了新字段,而不是删除和创建所有表的命令。

更新2:

我遵循了本教程,当尝试在多个数据上下文上进行迁移时,它似乎更清楚地解释了事情:

http://www.dotnet-tricks.com/Tutorial/entityframework/2VOa140214-Entity-Framework-6-Code-First-Migrations-with-Multiple-Data-Contexts.html

我运行了这个命令:

Enable-Migrations -ContextTypeName MyProject.Models.ApplicationDbContext

创建了以下配置:

internal sealed class Configuration : DbMigrationsConfiguration<MyProject.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}

protected override void Seed(MyProject.Models.ApplicationDbContext context)
{
}
}

...看起来不错。然后我运行了这个:

Add-Migration -Configuration MyProject.Data.Migrations.Configuration MigrationIdentity

...生成此文件:

namespace MyProject.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;

public partial class MigrationIdentity : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.MyPortfolio",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 45),
IsMaster = c.Boolean(nullable: false),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);

...my other non-identity entities...

CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");

...other Identity entities/tables...

}

public override void Down()
{
...everything you'd expect...
}
}
}

太棒了!所有表/实体都在一个文件中!所以我运行了它:

Update-Database -Configuration MyProject.Data.Migrations.Configuration -Verbose

...然后砰!它在 MyPortfolio 表上生成了具有 UserId FK 的所有表。世界似乎一切都美好。现在没有什么可以阻止我了!然后我运行它并得到这个异常:

One or more validation errors were detected during model generation:

System.Data.Entity.ModelConfiguration.ModelValidationException

MyProject.Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. MyProject.Data.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined. IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

快速的谷歌让我自然地回到了Stack Exchange:EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

已接受的答案概述了一系列新的可能的播放角度,以尝试使其正常工作。这让我回到了最初的问题。我可以在不进行迁移的情况下执行此操作吗?无论如何,这可能吗?鉴于其随之而来的复杂程度,如果没有的话,我正在认真讨论“滚动我自己的”身份验证。我已经花费了大量时间尝试简单地将代码优先实体与身份用户联系起来。每扇新门都意味着另外两扇门需要通过。这似乎不值得……但也许他们会在下一个版本中对此进行一些清理。

最佳答案

您可以在OnModelCreating中指定关系。

尝试每个数据库使用一个 DbContext。通常,您会为不同的数据库而不是相同的数据库创建不同 DbContexts

将所有实体移至 ApplicationDbContext 中,并按照以下说明进行操作。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("name=MyDataModel", throwIfV1Schema: false)
{
}

public DbSet<MyPortfolio> Portfolios { get; set; }
// The rest of the entities
// goes here

public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

modelBuilder.Entity<MyPortfolio>()
.HasRequired(m => m.User )
.WithOptional(m => m.Portfolio )
.Map(m => { m.MapKey("UserId"); });

base.OnModelCreating(modelBuilder);

//sql output log
Database.Log = s => Debug.Write(s);
}

}

与您必须更新数据库相比,通过迁移,这非常容易。在 Visual Studio 中打开包管理器控制台并按顺序输入此命令。

Enable-Migration
Add-Migration UserPortofolioRelation`
Update-Database

关于asp.net-mvc - ASP.NET Identity 2.1 和 EF 6 - 应用程序用户与其他实体的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29614476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com