簡體   English   中英

FK 和 PK 實體框架核心之間的沖突

[英]Conflict between FK an PK Entity Framework Core

我正在嘗試使用 Entity Framework 核心構建一個 web 應用程序,我創建了兩個模型Category an Pie ,我做了所有事情,包括 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}

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

Startup類的Configure方法:

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


 }

這是因為你添加了

public int CategoryId { get; set; }

pie實體框架在您添加時自行處理關系

public virtual Category Category { get; set; }

在您的情況下,當您添加CategoryId它需要categoryId因為它沒有設置為 null 這就是為什么它給出異常,因此您可以將CategoryId設置為nullable int

public int? CategoryId { get; set; }

或者您可以讓實體框架將其作為nullable為您處理

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM