我正在尝试使用Entity Framework核心构建一个Web应用程序,我创建了两个模型Category
和Pie
,我做了所有事情,包括DbContext一个依赖注入,我创建了一个{{ 1}}类来检查数据库是否为空,如果这是真的,它将插入一些数据,问题是当我运行应用程序时我得到一个异常,好像在Categories表中的主键和外键之间存在冲突馅饼表,这是例外:
DbInializer
这是Pie类:
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}
...这里是分类:
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; }
}
Startup类的Configure方法:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public List<Pie> Pies { get; set; }
}
DbInitializer类:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
DbInitializer.Seed(app);
}
答案 0 :(得分:3)
这是因为你添加了
public int CategoryId { get; set; }
pie
实体框架中的在您添加
时自行处理关系public virtual Category Category { get; set; }
在您添加CategoryId
的情况下,它期望categoryId
,因为它未设置为null,这就是为什么它会给出异常,因此您可以将CategoryId
设置为nullable int
public int? CategoryId { get; set; }
或者您可以让实体框架为您nullable
处理它