我開始一個全新的.NET MVC項目,首先針對EF 6和.NET 4.5使用代碼。我也想使用Identity框架,並在我的項目的上下文配置中擴展Identity基類。 (不知道我說的都是正確的......我是一位經驗豐富的C#/ .NET開發人員,對於MVC,EF和身份來說有點新鮮。)在EF中集成和擴展.NET標識類(代碼優先)
我的問題:有些事情是錯誤的。在試圖產生一個新的遷移,我得到錯誤:
POST.Data.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
POST.Data.Models.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.
好了,所以,我在我的項目,一個用於身份類,其他爲一切兩個上下文。相同的數據庫,並且任何上下文都不涉及其他任何內容。我正是如此定義實體:
public class ApplicationUser : IdentityUser { }
public class ApplicationRole : IdentityRole { }
public class ApplicationUserRole : IdentityUserRole { }
public class ApplicationUserClaim : IdentityUserClaim { }
public class ApplicationUserLogin : IdentityUserLogin { }
然後,我有一個上下文類是這樣的:
public partial class IdentityContext : IdentityDbContext
{
public IdentityContext() : base() { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(ul => ul.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(ur => new { ur.RoleId, ur.UserId });
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<ApplicationUserClaim> ApplicationUserClaims { get; set; }
public DbSet<ApplicationUserLogin> ApplicationUserLogins { get; set; }
public DbSet<ApplicationRole> ApplicationRoles { get; set; }
public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; }
}
不知道它甚至事項,但我的配置事情是這樣的:
internal sealed class Configuration : DbMigrationsConfiguration<POST.Data.Models.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"ContextMigrations";
}
protected override void Seed(POST.Data.Models.Context context) {}
}
這將會建立起來,但是如果沒有這些錯誤,我不能產生遷移,並且我對有限的知識和對所有細節的理解都很困惑。
好的,所以這是我正在採取的原始方向,但創建了單獨的子類,因爲我以爲我想在將來擴展它們,我現在也可以讓我的生活變得輕鬆。但是我坦白地說,僅僅讓它獨自存在就是一種邏輯。 –
但我有這個問題,我希望我正確地說出這個問題:如果我沒有一個從IdentityDbContext繼承的單獨的上下文,而是從DbContext繼承,那麼如何創建基類的Identity類所有這些具體實體將會在我的數據庫中生成?我的意思是,在某些時候,我需要說我希望創建AspNet Identity表,對嗎?又怎樣?我有我的其他背景像MainContext:DbContext;應該是MainContext:IdentityDbContext? –
好的,沒關係。我相信我有這個想法...... :-P你只需創建單獨的上下文並將其保留爲空。 –