【问题标题】:Code has no errors, Database is connected but An error occurred while updating the entries. See the inner exception for details代码没有错误,数据库已连接,但更新条目时发生错误。有关详细信息,请参阅内部异常
【发布时间】:2016-03-02 08:04:37
【问题描述】:

我正在编写 MVC Web 应用程序,并尝试使用 Code First 迁移方法填充我的数据库。

我在包管理器控制台上执行了以下命令

启用迁移 -contexttypename 问题上下文

添加迁移初始创建

更新数据库

然后我得到`更新条目时发生错误。有关详细信息,请参阅内部异常。

我的代码没有错误,我的数据库已连接,但数据库资源管理器中没有显示表

有人可以指点我应该看哪里或哪里出了问题吗?

> PM> update-database Specify the '-Verbose' flag to view the SQL
> statements being applied to the target database. No pending explicit
> migrations. Unable to update database to match the current model
> because there are pending changes and automatic migration is disabled.
> Either write the pending model changes to a code-based migration or
> enable automatic migration. Set
> DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable
> automatic migration. You can use the Add-Migration command to write
> the pending model changes to a code-based migration.

Configuration.cs(种子方法)

namespace RecreationalServicesTicketingSystem.Migrations
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using RecreationalServicesTicketingSystem.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<RecreationalServicesTicketingSystem.DAL.IssueContext>
    {
        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") },
                new User { FirstMidName = "Andy", LastName = "Domagas",    
                    EnrollmentDate = DateTime.Parse("2016-02-18") },
                new User { FirstMidName = "Denis",   LastName = "Djohar",     
                    EnrollmentDate = DateTime.Parse("2016-02-18") },
                new User { FirstMidName = "Christine",   LastName = "West",     
                    EnrollmentDate = DateTime.Parse("2016-02-18") },

            };

            users.ForEach(s => context.Users.AddOrUpdate(p => p.LastName, 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();





            var administrator = new List<Administrator>
            {
                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();
        }
    }
}

用户.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; }
    //Setting up relationships A use can apply for any number of tickets, so Tickets is defined as a collection of Ticket entities.
    public virtual ICollection<Ticket> Users { get; set; }

}

Ticket.cs

public class Ticket
    {
        public string Issue { get; set; }
        [DisplayFormat(NullDisplayText = "No Priority")]
        public Priority? Priority { get; set; }
        //Category One to Many Ticket
        public int CategoryID { get; set; }
        [ForeignKey("CategoryID")]
        public virtual Category Category { get; set; }
        //User (One to Many) Ticket
        public int UserID { get; set; }
        public int TicketID { get; set; }
        [ForeignKey("TicketID")]
        public virtual User User { get; set; }
        public int AdminID { get; set; }
        public virtual ICollection<Administrator> Administrators { get; set; }

    }

仓库.cs

public class Depot
{
    //Do I need DepotID??
    public int DepotID { get; set; }

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

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

}

Department.cs

public class Department
{
    //Do I need DepartmentID?
    public int DepartmentID { get; set; }

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

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

Category.cs

public class Category
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CategoryID { get; set; }
    public string Title { get; set; }

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

Administrator.cs

public class Administrator
{
    [Key, ForeignKey("User")]
    public int UserID { get; set; }
    public int AdminID { get; set; }
    public int TicketID { get; set; }        
    [StringLength(50)]
    public string AdminRole { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }
    public virtual User User { get; set; }
}

【问题讨论】:

  • 在种子方法的开头添加if (System.Diagnostics.Debugger.IsAttached == false) { System.Diagnostics.Debugger.Launch(); }
  • 发布您的表架构/模型。如果您通读该错误堆栈,则 DB 会为 FK_dbo.User_dbo.Department_DepartmentID 抛出外键冲突。由于您尚未提出架构,因此我假设 DepatmentId 是您的 User 表中的必需 FK 字段,并且您在查看用户时没有提供值。
  • P.S.将您的错误发布为文本,而不是图像。
  • @jmoerdyk 我发布了模型
  • @netaholic 它打开了 VWDExpress(调试)所以在 Configuration.cs 中我在 users.Foreach(s =&gt; context.Users.AddOrUpdate(p =&gt; p.LastName,s)); Error is DBUpdateException 下有一个错误 context.SaveChanges() 用户代码未处理`

标签: c# asp.net-mvc relational-database entity-framework-migrations


【解决方案1】:

从数据库抛出的错误是 FK_dbo.User_dbo.Department_DepartmentID 的外键违规。

您的Users 有:

public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; } 

一个不可为空的 int 作为外键,这意味着它是必需的。

Seed 方法中创建Users 时,您没有设置DepartmentId,因此违反了FK。

因此,您可以通过以下两种方式之一解决此问题:

Seed 方法中,您必须首先创建DepartmentList,并在创建属于该列表的User 时提供DepartmentId。就像您在创建 Ticket 时必须提供 UserIdCategoryId 一样。

您将DepartmentId 创建为可为空的:

public int? DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; } 

【讨论】:

  • 应该是什么?我是另一个问题的建议。我也不太确定如何使用 [Key,ForeignKey("DepartmentID")] !刚刚有人告诉我把它放在那里。
  • 从您的模型来看,User 上的 DepotId 也会遇到同样的问题。
  • 是的,它是必需的。所以我只需要复制并粘贴 `public int DepartmentID { get;放; } [ForeignKey("DepartmentID")] public virtual Department Department { get;放; }` 上面我的public int UserID { get;set;}??
  • 不,您必须在创建 Users 之前创建 DepartmentDepot 列表。
  • 在创建Users 时,您仍然没有提供DepartmentIdDepotId。并在定义部门和仓库时删除, Users = new List&lt;User&gt;(),EF 将处理该部分。并从 Depot 和 Deparment 模型中删除 public int UserID { get; set; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多