【问题标题】:Conflict between FK an PK Entity Framework CoreFK 和 PK 实体框架核心之间的冲突
【发布时间】:2017-02-25 15:15:51
【问题描述】:

我正在尝试使用 Entity Framework 核心构建一个 Web 应用程序,我创建了两个模型 CategoryPie,我做了所有事情,包括 DbContext 和依赖注入,我创建了一个 DbInializer 类来检查数据是否base 为空,如果这是真的,它将插入一些数据,问题是当我运行应用程序时出现异常,好像 Categories 表中的主键和 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}

这是 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; }
}

...这里是类别类:

public class Category
{
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public string Description { get; set; }
        public List<Pie> Pies { get; set; }
}

启动类的配置方法:

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

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();
        }


 }

【问题讨论】:

  • 是插入的时候出现这个错误吗?
  • 您以哪种方式配置实体之间的关系?
  • @Usman 调用 DbInitializer 类的 Seed 方法时发生异常
  • @brut 我使用代码优先方法
  • 我认为您必须分配从上下文中检索到的 Category 对象,因为如果您要添加类别,CategoryId 还没有准备好(直到您调用 SaveChanges)跨度>

标签: c# sql-server entity-framework asp.net-core-mvc


【解决方案1】:

这是因为你添加了

public int CategoryId { get; set; }

pie Entity Framework 在你添加时自己处理关系

public virtual Category Category { get; set; }

在您添加CategoryId 的情况下,它需要categoryId,因为它没有设置为null,这就是它给出异常的原因,所以您可以将CategoryId 设置为nullable int

public int? CategoryId { get; set; }

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

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2020-05-10
    • 2020-11-25
    • 2013-07-10
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多