【发布时间】:2016-03-10 05:13:11
【问题描述】:
在我的 Configuration.cs 的 Seed() 方法中,我在添加数据时遇到了一些错误:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
堆栈跟踪
at System.Data.Entity.Internal.InternalContext.SaveChanges()
我的带有种子数据的 Configuration.cs 文件:
namespace MarginWorkbenchNG.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
internal sealed class Configuration : DbMigrationsConfiguration<MarginWorkbenchNG.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true; // added - BM:
ContextKey = "MarginWorkbenchNG.Models.ApplicationDbContext";
}
protected override void Seed(MarginWorkbenchNG.Models.ApplicationDbContext context)
{
var hasher = new PasswordHasher();
// **** Causing "Validation failed" errors on line 80 of AccountController.cs ****
context.Roles.AddOrUpdate(
new IdentityRole { Name = "SystemAdministrator" }
);
context.Users.AddOrUpdate(
new Models.ApplicationUser { Company = "ICAP", EmailConfirmed = true, FirstName = "Admin", LastName = "Demo", UserName = "admin@rzr.com", Email = "admin@rzr-risk.com", PasswordHash = hasher.HashPassword("test123") },
new Models.ApplicationUser { Company = "ICAP", EmailConfirmed = true, FirstName = "Trader", LastName = "Demo", UserName = "trade@rzr.com", Email = "trade@rzr.com", PasswordHash = hasher.HashPassword("test123") }
);
context.SaveChanges();
}
}
}
我在IdentityModels.cs 中对我的ApplicationUser 类进行了一些小的更改,并且我当然可以在修改此类时看到表架构更改(即我将自动迁移设置为true)。但是,Seed() 方法失败了。
public class ApplicationUser : IdentityUser
{
// added Company, Name to profile - BM:
public string Company { get; set; }
public string FirstName { get; set; }
public string LastName{ get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
仅供参考:在某些时候,当AppNetUsers 表为空时,种子数据成功。
但是,现在完全不一致。我已经删除了AppNetUsers 中的记录,但是 Seed() 方法仍然失败。我不明白。
**** 更新 **** 如果我在 web.config 文件中更改数据库名称,我可以强制它创建一个全新的数据库 - 并且 seed() 数据工作正常!
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=MyDevBox;Initial Catalog=TestDB2;Integrated Security=True" providerName="System.Data.SqlClient" />
但是,当我尝试重新创建数据库时,我仍然不理解上述 Seed() 方法中的异常?
谢谢你, 鲍勃
【问题讨论】:
-
您能否包含尝试播种(但失败)时发生的控制台输出?并包括您的 Seed 方法。
-
请在seed()方法中提供失败的源代码?
-
@toddmo,当然可以。我忘记了实际的种子数据。
-
是的,使用 RoleManager 和 UserManager。另一方面,当您使用 AddOrUpdate 时,您应该提供该字段来检查是否存在:stackoverflow.com/questions/10007351/…
标签: asp.net-mvc entity-framework