2016-03-03 3 views
0

У меня возникла эта ошибка, когда я пытаюсь обновить мою базу данных до совокупности моих таблиц.MVC с сопоставлением реляционных баз данных EF

PM> Обновление базы данных-

No pending explicit migrations. 
Running Seed method. 
System.InvalidOperationException: Sequence contains no matching element 
    at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate) 
    at RecreationServicesTicketingSystem.Migrations.Configuration.Seed(IssueContext context) in C:\Users\jwan\Documents\Visual Studio 2012\Projects\RecreationServicesTicketingSystem\RecreationServicesTicketingSystem\Migrations\Configuration.cs:line 60 
    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) 
Sequence contains no matching element 

Я был вокруг и прибегая к помощи никто не кажется, подобный вопрос. Это на этой линии var administrator = new List<Administrator> Я поставил указатель относительно того, где находится линия 60.

Click Here Tables from SQL Server Management Studio

Click Here for Entity Models

public Configuration() 
     { 
      AutomaticMigrationsEnabled = false; 
     } 
    protected override void Seed(RecreationalServicesTicketingSystem.DAL.IssueContext context) 
    { 

     var departments = new List<Department> 
     { 
      new Department { DepartmentID = 1, Name = "IT"}, 
      new Department { DepartmentID = 2, Name = "Admin" }, 
      new Department { DepartmentID = 3, Name = "Human Resources"}, 
      new Department { DepartmentID = 4, Name = "Mechanics" }, 
      new Department { DepartmentID = 5, Name = "Directors" }, 
      new Department { DepartmentID = 6, Name = "Operations"} 

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


     var depots = new List<Depot> 
     { 
      new Depot { DepotID = 1, Name = "Porana"}, 
      new Depot { DepotID = 2, Name = "Far North"}, 


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

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

}; 

     var administrator = new List<Administrator> <-- LINE 60 
     { 
      new Administrator {AdminID = 1, AdminRole = "Administrator LVL1", User = users.Single (s => s.UserID == 1), 
      Tickets = new List<Ticket>() }, 
      new Administrator {AdminID = 2, AdminRole = "Administrator LVL2", User = users.Single (s => s.UserID == 2), 
      Tickets = new List<Ticket>() }, 
      new Administrator {AdminID = 3, AdminRole = "Administrator LVL3", User = users.Single (s => s.UserID == 3), 
      Tickets = new List<Ticket>() } 

     }; 
     administrator.ForEach(s => context.Administrators.AddOrUpdate(p => p.AdminID, s)); 
     context.SaveChanges(); 

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

     var tickets = new List<Ticket> 
     { 
      new Ticket { 
       UserID = users.Single(s => s.LastName == "Wan").UserID, 
       CategoryID = categories.Single(c => c.Title == "Con-X").CategoryID, 
       Issue = ("Test Error 1"), 
       Priority = Priority.High 
      }, 
      new Ticket { 
       UserID = users.Single(s => s.LastName == "Wan").UserID, 
       CategoryID = categories.Single(c => c.Title == "Desktop").CategoryID, 
       Issue = ("Test Error 2"), 
       Priority = Priority.Med 
      }, 
     }; 


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

    } 
} 

User.cs

public class User 
    { 

     public int UserID { 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; } 

     [DataType(DataType.Date)] 
     [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 
     public DateTime EnrollmentDate { get; set; } 

     public string FullName 
     { 
      get { return LastName + ", " + FirstMidName; } 
     } 
     public int AdministratorID { get; set; } 
     [ForeignKey("AdministratorID")] 
     public virtual Administrator Administrator { 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 int TicketID { get; set; } 

     public virtual ICollection<Ticket> Users { get; set; } 

    } 

Department.cs

public class Department 
{ 

    public int DepartmentID { get; set; } 

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

    public virtual ICollection<User> Users { get; set; } 
} 

Depot.cs

public class Depot 
{ 

    public int DepotID { get; set; } 
    [StringLength(50, MinimumLength = 1)] 
    public string Name { get; set; } 
    public virtual ICollection<User> Users { get; set; } 

} 

ответ

1

При создании своих пользователей вы не указываете, к какому подразделению они принадлежат. Это означает, что для поля int по умолчанию оно равно 0. В вашей базе данных нет отдела с идентификатором 0, поэтому иностранный ключевое ограничение нарушено. Попробуйте что-то вроде:

var users = new List<User> 
     { 
      new User { FirstMidName = "Jason", LastName = "Wan", 
       EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentId = 1 }, 
      new User { FirstMidName = "Andy", LastName = "Domagas", 
       EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentId = 1 }, 
      new User { FirstMidName = "Denis", LastName = "Djohar", 
       EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentId = 1 }, 
      new User { FirstMidName = "Christine", LastName = "West", 
       EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentId = 1 }, 

     }; 

Update для решения вопроса депо:

Вы создаете склады, однако линия, которая добавляет их в контексте ссылки отделов вместо складов:

var depots = new List<Depot> 
     { 
      new Depot { DepotID = 1, Name = "Porana"}, 
      new Depot { DepotID = 2, Name = "Far North"}, 


     }; 
     departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));// should be: 
     depots.ForEach(s => context.Depots.AddOrUpdate(p => p.Name, s)); 
     context.SaveChanges(); 
+0

Да, что решило проблему отдела СПАСИБО, и теперь у меня есть такая же ошибка, но она говорит о депотиде. Я применил ту же концепцию, но это неверно. 'Оператор INSERT противоречил ограничению FOREIGN KEY" FK_dbo.User_dbo.Depot_DepotID ". Конфликт произошел в базе данных «LeisureServicesTicketingSystem.DAL.IssueContext», таблице «dbo.Depot», в столбце «DepotID». «Проверьте мой вопрос для обновленной версии. – TykiMikk

+0

Не похоже, что вы создаете любые депо, не забудьте создать их, прежде чем ссылаться на них в своем пользователе. – JanR

+0

обновил мой ответ, извините, был на моем телефоне до – JanR

Смежные вопросы