添加新类后迁移文件缩小

本文关键字:文件 缩小 迁移 新类 添加 | 更新日期: 2023-09-27 18:36:57

我不知道为什么我的迁移文件只有 2 行用于上下方法的代码,但我之前有 3 个类的代码更多。如果我错误地映射我的新类会导致这个结果吗?

我希望每个用户只有 1 个与他们相关的部门。

我尝试执行更新数据库,但收到此错误代码(只是重要部分的片段)

更新条目时出错。查看内部异常 了解详情。---> System.Data.SqlClient.SqlException: The INSERT 语句与外键约束冲突 "FK_dbo。User_dbo。Department_DepartmentID"。冲突发生在 数据库"娱乐服务票务系统.DAL.问题上下文",表 "哎呀。部门","部门 ID"一栏。

配置.cs有5个类

  internal sealed class Configuration : DbMigrationsConfiguration<RecreationalServicesTicketingSystem.DAL.IssueContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            //         AutomaticMigrationDataLossAllowed = true;
        }
        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();
        }
    }

种子方法与 5 类

 public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            DropColumn("dbo.Department", "UserID");
            DropColumn("dbo.Depot", "UserID");
        }
        public override void Down()
        {
            AddColumn("dbo.Depot", "UserID", c => c.Int(nullable: false));
            AddColumn("dbo.Department", "UserID", c => c.Int(nullable: false));
        }
    }

种子方法 3 类

namespace RecreationalServicesTicketingSystem.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.User",
                c => new
                {
                    UserID = c.Int(nullable: false, identity: true),
                    LastName = c.String(),
                    FirstMidName = c.String(),
                    EnrollmentDate = c.DateTime(nullable: false),
                })
                .PrimaryKey(t => t.UserID);
            CreateTable(
                "dbo.Ticket",
                c => new
                {
                    TicketID = c.Int(nullable: false, identity: true),
                    CategoryID = c.Int(nullable: false),
                    UserID = c.Int(nullable: false),
                    Issue = c.String(),
                    Priority = c.Int(),
                })
                .PrimaryKey(t => t.TicketID)
                .ForeignKey("dbo.Category", t => t.CategoryID, cascadeDelete: true)
                .ForeignKey("dbo.User", t => t.UserID, cascadeDelete: true)
                .Index(t => t.CategoryID)
                .Index(t => t.UserID);
            CreateTable(
                "dbo.Category",
                c => new
                {
                    CategoryID = c.Int(nullable: false),
                    Title = c.String(),
                })
                .PrimaryKey(t => t.CategoryID);
        }
        public override void Down()
        {
            DropIndex("dbo.Ticket", new[] { "UserID" });
            DropIndex("dbo.Ticket", new[] { "CategoryID" });
            DropForeignKey("dbo.Ticket", "UserID", "dbo.User");
            DropForeignKey("dbo.Ticket", "CategoryID", "dbo.Category");
            DropTable("dbo.Category");
            DropTable("dbo.Ticket");
            DropTable("dbo.User");
        }
    }
}

部门.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; }
    }

用户.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; }
    }

添加新类后迁移文件缩小

您的 DepartmentId 和 UserId 是 int,因此对于 SQL Server,它们将是标识列。你不能在没有"SET IDENTITY_INSERT [dbo] 的情况下将它们显式插入到你的 Seed() 方法中。[部门]ON"或标记列,使其不会成为标识 [DatabaseGenerated (DatabaseGenerated Option.None)]。您也可以在插入时排除 Id,然后让 SQL 分配它。

关于您的 2 次迁移 - 它们是累加的而不是累积的。因此,第二次迁移将当前模型与上次迁移进行比较并生成差异。