[英]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.