FK 和 PK 实体框架核心之间的冲突

Bou*_*ieb 1 c# sql-server entity-framework asp.net-core-mvc

我试图建立与实体框架核心的Web应用程序,我创建了两个型号CategoryPie,我做的所有事情,包括的DbContext的依赖注入,我创建了一个DbInializer类来检查,如果数据库是空的,如果这是真的,那会插入一些数据,问题是当我运行应用程序时出现异常,好像类别表中的主键和 Pies 表中的外键之间存在冲突,这是异常:

 System.Data.SqlClient.SqlException: The MERGE statement conflicted with the FOREIGN KEY constraint "FK_Pies_Categories_CategoryId".The conflict occurred in database "ShopDb", table "dbo.Categories", column 'CategoryId'.
     at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean & dataReady)
   at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean & moreRows)
   at System.Data.SqlClient.SqlDataReader.TryHasMoreResults(Boolean & moreResults)
   at System.Data.SqlClient.SqlDataReader.TryNextResult(Boolean & more)
   at System.Data.SqlClient.SqlDataReader.NextResult()
   at Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.Consume(DbDataReader reader)
ClientConnectionId: 775a7294 - 531a - 44cc - 8fbc - 29d293c339d5
         Error Number: 547,State: 0,Class: 16}
Run Code Online (Sandbox Code Playgroud)

这是 Pie 类:

 public class Pie
 {
        public int PieId { get; set; }
        public string Name { get; set; }
        public string ShortDescrition { get; set; }
        public string LongDescription { get; set; }
        public string AllegryInformation { get; set; }
        public string ImageUrl { get; set; }
        public string ImageThumbnailUrl { get; set; }
        public bool IsPieOfTheWeek { get; set; }
        public bool InStock { get; set; }
        public decimal Price { get; set; }
        public int CategoryId { get; set; }
        public virtual Category Category { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

...这里是类别类:

public class Category
{
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public string Description { get; set; }
        public List<Pie> Pies { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Startup类的Configure方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
            DbInitializer.Seed(app);
        }
Run Code Online (Sandbox Code Playgroud)

DbInitializer 类:

 public class DbInitializer
 {

        public static void Seed(IApplicationBuilder applicationBuilder)
        {
            AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();
            if (!context.Categories.Any())
            {
                context.AddRange(
                        new Category { CategoryName = "First Pie", Description="Descriptionslqdfq vdfhsqdqsdhfs qsdhf" },
                        new Category { CategoryName = "Cheese Cackes", Description = "Descriptionslqdfq vdfhsqdqsdhfs qsdhf" },
                        new Category { CategoryName = "Saesonal Pie", Description = "Descriptionslqdfq vdfhsqdqsdhfs qsdhf" });
            }
            if (!context.Pies.Any())
            {
                context.AddRange(new Pie { Name = "Apple Pie", ShortDescrition = "short description", LongDescription = "Long description", AllegryInformation = "sflqjq", ImageUrl = "#", IsPieOfTheWeek = true, InStock = true, Price = 15.65M },
                    new Pie { Name = "Apple Pie", ShortDescrition = "short description", LongDescription = "Long description", AllegryInformation = "sflqjq", ImageUrl = "#", IsPieOfTheWeek = true, InStock = true, Price = 15.65M },
                    new Pie { Name = "Apple Pie", ShortDescrition = "short description", LongDescription = "Long description", AllegryInformation = "sflqjq", ImageUrl = "#", IsPieOfTheWeek = true, InStock = true, Price = 15.65M },
                    new Pie { Name = "Apple Pie", ShortDescrition = "short description", LongDescription = "Long description", AllegryInformation = "sflqjq", ImageUrl = "#", IsPieOfTheWeek = true, InStock = true, Price = 15.65M },
                    new Pie { Name = "Apple Pie", ShortDescrition = "short description", LongDescription = "Long description", AllegryInformation = "sflqjq", ImageUrl = "#", IsPieOfTheWeek = true, InStock = true, Price = 15.65M });
            }
            context.SaveChanges();
        }


 }
Run Code Online (Sandbox Code Playgroud)

Usm*_*man 7

这是因为你添加了

public int CategoryId { get; set; }
Run Code Online (Sandbox Code Playgroud)

pie实体框架中添加时自行处理关系

public virtual Category Category { get; set; }
Run Code Online (Sandbox Code Playgroud)

在你的情况下,当你添加CategoryId它期望categoryId因为它没有设置为 null 这就是为什么它给出异常所以你可以设置CategoryIdnullable int

public int? CategoryId { get; set; }
Run Code Online (Sandbox Code Playgroud)

或者您可以让实体框架nullable为您处理它