2016-03-28 25 views
2

Veritabanımı Seed Yöntemimi kullanarak doldurmak için güncelleme veritabanı alıyorum.MVC5 Doğrulama bir veya daha fazla varlık için başarısız oldu. Daha fazla bilgi için 'EntityValidationErrors' özelliğine bakın

EF uygulaması ile MVC4 kodluyordum ve şu anda EF ile MVC5'e yükseltme işleminde bulunuyor. MVC4'te daha önce User.cs adında bir sınıf oluşturmak zorunda kaldım, ancak IdentityUser'den türetmek için User sınıfımıza ihtiyaç duyarız.

var users = new List<User> 

var users = new List<ApplicationUser> 

ve

new User{ FirstMi.... 

için

için: Ben MVC4 yapılandırma dosyası ile yaptı ve sadece değişmiş gibi kodun aynısını kullanıyorum

new ApplicationUser { FirstMi.... 

hata burada

users.ForEach (s => context.Users.AddOrUpdate (N => p.FirstMidName, s)) olan hat 61 üzerinde; context.SaveChanges()

PM> Update-Database 
Specify the '-Verbose' flag to view the SQL statements being applied to the target database. 
No pending explicit migrations. 
Running Seed method. 
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. 
    at System.Data.Entity.Internal.InternalContext.SaveChanges() 
    at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 
    at System.Data.Entity.DbContext.SaveChanges() 
    at RecreationalServicesTicketingSystem.Migrations.Configuration.Seed(ApplicationDbContext context) in C:\Users\Jason\Documents\Visual Studio 2015\Projects\RecreationalServicesTicketingSystem\RecreationalServicesTicketingSystem\Migrations\Configuration.cs:line 62 
    at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context) 
    at System.Data.Entity.Migrations.DbMigrator.SeedDatabase() 
    at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase() 
    at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) 
    at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) 
    at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) 
    at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b() 
    at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) 
    at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) 
    at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) 
    at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) 
    at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run() 
    at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) 
    at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) 
    at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) 
    at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force) 
    at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0() 
    at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command) 
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. 

IdentityModel.cs hata olarak

public class ApplicationUser 
: IdentityUser<int, ApplicationUserLogin, 
    ApplicationUserRole, ApplicationUserClaim>, IUser<int> 
{ 
    public async Task<ClaimsIdentity> 
     GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager) 
    { 
     var userIdentity = await manager 
      .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     return userIdentity; 
    } 


    public bool IsAdministrator { get; set; } 
    [StringLength(50, MinimumLength = 1)] 

    public string LastName { get; set; } 
    [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")] 

    [Column("FirstName")] 
    public string FirstMidName { get; set; } 

    public string FullName 
    { 
     get { return FirstMidName + " " + LastName; } 
    } 
    [DataType(DataType.Date)] 
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 
    public DateTime EnrollmentDate { get; set; } 
    public int DepartmentID { get; set; } 
    [ForeignKey("DepartmentID")] 
    public virtual Department Department { get; set; } 
    public int DepotID { get; set; } 
    [ForeignKey("DepotID")] 
    public virtual Depot Depot { get; set; } 
    public virtual ICollection<Ticket> Tickets { get; set; } 
} 

Configuration.cs (Tohum Yöntemi)

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

    protected override void Seed(ApplicationDbContext context) 
    { 
     var departments = new List<Department> 
     { 
      new Department { DepartmentID = 1, DepartmentName = "IT"}, 
      new Department { DepartmentID = 2, DepartmentName = "Menzit Admin" }, 
      new Department { DepartmentID = 3, DepartmentName = "Human Resources"}, 
      new Department { DepartmentID = 4, DepartmentName = "Mechanics" }, 
      new Department { DepartmentID = 5, DepartmentName = "Directors" }, 
      new Department { DepartmentID = 6, DepartmentName = "Operations"} 

     }; 
     departments.ForEach(s => context.Departments.AddOrUpdate(p => p.DepartmentName, s)); 
     context.SaveChanges(); 


     var depots = new List<Depot> 
     { 
      new Depot { DepotID = 1, DepotName = "Porana"}, 
      new Depot { DepotID = 2, DepotName = "Far North"}, 
      new Depot { DepotID = 3, DepotName = "Horowhenua"}, 
      new Depot { DepotID = 4, DepotName = "Manawatu"}, 
      new Depot { DepotID = 5, DepotName = "Silverdale"}, 
      new Depot { DepotID = 6, DepotName = "Christchurch"}, 

     }; 
     depots.ForEach(s => context.Depots.AddOrUpdate(p => p.DepotName, s)); 
     context.SaveChanges(); 

      var users = new List<ApplicationUser> 
    { 
     new ApplicationUser { FirstMidName = "Jason", LastName = "Wan", 
      EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1, DepotID = 1,IsAdministrator = true}, 
     new ApplicationUser { FirstMidName = "Andy", LastName = "Domagas", 
      EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1,IsAdministrator = true}, 
     new ApplicationUser { FirstMidName = "Denis", LastName = "Djohar", 
      EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1 ,DepotID = 1,IsAdministrator = true }, 
     new ApplicationUser { FirstMidName = "Christine", LastName = "West", 
      EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 2, DepotID = 3,IsAdministrator = false}, 

    }; 

      users.ForEach(s => context.Users.AddOrUpdate(p => p.FirstMidName, s)); 
      context.SaveChanges(); <--ERROR HERE 

      users.ForEach(s => context.Users.AddOrUpdate(p => p.LastName, s)); 
      context.SaveChanges(); 



     var categories = new List<Category> 
     { 
      new Category {CategoryID = 0001, CategoryName = "Desktop"}, 
      new Category {CategoryID = 0002, CategoryName = "Mobile"}, 
      new Category {CategoryID = 0003, CategoryName = "Menzits"}, 
      new Category {CategoryID = 0004, CategoryName = "XMPRO"}, 
      new Category {CategoryID = 0005, CategoryName = "Con-X"}, 
      new Category {CategoryID = 0006, CategoryName = "Promapp"}, 
      new Category {CategoryID = 0007, CategoryName = "QGIS"}, 
     }; 
     categories.ForEach(s => context.Categories.AddOrUpdate(p => p.CategoryName, s)); 
     context.SaveChanges(); 

     var tickets = new List<Ticket> 
     { 
      new Ticket { 
       UserID = users.Single(s => s.LastName == "Wan").Id, //UserID 
       CategoryID = categories.Single(c => c.CategoryName == "Con-X").CategoryID, 
       Issue = ("Con-X Login Error"), 
       Priority = Priority.High 
      }, 
      new Ticket { 
       UserID = users.Single(s => s.LastName == "Wan").Id, //UserID 
       CategoryID = categories.Single(c => c.CategoryName == "Desktop").CategoryID, 
       Issue = ("Can't remote access C0123"), 
       Priority = Priority.Med 
      }, 
     }; 


     foreach (Ticket e in tickets) 
     { 
      var ticketInDataBase = context.Tickets.Where(
       s => 
        s.User.Id == e.UserID && //UserID 
        s.Category.CategoryID == e.CategoryID).SingleOrDefault(); 
      if (ticketInDataBase == null) 
      { 
       context.Tickets.Add(e); 
      } 
     } 
     context.SaveChanges(); 

    } 




} 
+1

'ApplicationUser' KullanıcıAdı 'özelliği gerekli bir alandır. Bunu Tohum yönteminizde doldurun. –

cevap

4

basit bir çözüm izle penceresine bu satırı eklemek olacaktır:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors 

ama benim tahminim hata ApplicationUser 'ın KullanıcıAdı özelliğinden geldiğini olurdu yapmanız gerekenler Yeni bir kullanıcı eklerken bir değer verin :)

Umarım yardımcı olur.

+0

Bu harika, teşekkürler! SaveChanges'i geçersiz kılmanın ve özel durum ayrıntılarını yakalamanın ve genişletmenin farkındaydım. Ama şu anda EF Database-First (edmx) yaklaşımını kullanıyorum ve bu oluşturulan sınıflar ve ne ile uğraşmak istemedim. Bu bir çekicilik gibi çalışır! – Jiveman

+0

dude, bu oluşturulan sınıflarla uğraşmak zorundasınız ama bunu aptalca yapmayın, sadece sınıfları oluşturmak için kullanılan dosyayı değiştirin :) – theMost1ted

3

(Pasaj zaman kullanıcı sınıfını içeren) Varlık doğrulama hatalarını denetlemeniz gerektiğini söylüyor,

try 
     { 
      db.Entity.Add(entity); 
      db.SaveChanges(); 
     } 
     catch (DbEntityValidationException dbEx) 
     { 
      foreach (var validationErrors in dbEx.EntityValidationErrors) 
      { 
       foreach (var validationError in validationErrors.ValidationErrors) 
       { 
        System.Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); 
       } 
      } 
     } 
İlgili konular