[英]Error updating One to One relation Entity Framework Core
When I update entity Framework row entry which has one to one relationship to another table.当我更新与另一个表具有一对一关系的实体框架行条目时。 I get this error on _context.SaveChanges();
我在_context.SaveChanges();
. . I have a class called NewsletterComponents
with one-to-one relation with NewsletterNewPlants
.我有一个名为NewsletterComponents
的 class 与NewsletterNewPlants
一对一的关系。 Not sure why the row fails to update throwing duplicate errors.不确定为什么该行无法更新并引发重复错误。 Should I delete it first then reinsert it?我应该先删除它然后重新插入它吗?
Error Message错误信息
SqlException: Cannot insert duplicate key row in object 'dbo.NewsletterNewPlants' with unique index 'IX_NewsletterNewPlants_NewPlantComponentId'. SqlException:无法在具有唯一索引“IX_NewsletterNewPlants_NewPlantComponentId”的 object“dbo.NewsletterNewPlants”中插入重复的键行。 The duplicate key value is (169).重复键值为 (169)。
OnPostUPdate Method OnPostUPdate 方法
public IActionResult OnPostUpdateComponent(NewsletterComponents component, int? newsId, int? shortArticleId)
{
var dbComponent = _context.NewsletterComponents.Find(component.NewsletterComponentId);
if (dbComponent == null)
{
return RedirectToPage("./Index");
}
dbComponent.NewsletterNewPlants = component.newsletterNewPlants;
dbComponent.NewsletterComponentSubline = component.NewsletterComponentSubline;
dbComponent.NewsletterComponentHeadline = component.NewsletterComponentHeadline;
_context.Update(dbComponent);
_context.SaveChanges();
return RedirectToPage(new { id = dbComponent.NewsletterComponentId});
}
Parent NewsletterComponents Model父通讯组件 Model
public partial class NewsletterComponents
{
public int NewsletterComponentId { get; set; }
public string ApplicationId { get; set; }
public string NewsletterComponentHeadline { get; set; }
public string NewsletterComponentSubline { get; set; }
public virtual NewsletterNewPlants NewsletterNewPlants { get; set; }
}
Child NewsletterNewPlants Model儿童通讯NewPlants Model
public class NewsletterNewPlants
{
[Key]
public int Id { get; set; }
[ForeignKey("NewsletterComponents")]
public int NewPlantComponentId { get; set; }
public int? NewPlant1 { get; set; }
public string NewPlant1SubHeadline { get; set; }
public int? NewPlant2 { get; set; }
public string NewPlant2SubHeadline { get; set; }
public int? NewPlant3 { get; set; }
public string NewPlant3SubHeadline { get; set; }
public string NewPlantMonth { get; set; }
public virtual NewsletterComponents NewsletterComponents { get; set; }
}
I was getting only NewsletterComponents
I modified the code to get a reference of newsletterNewPlants
also.我只得到NewsletterComponents
我修改了代码以获得newsletterNewPlants
的参考。
I changed the following line我更改了以下行
var dbComponent = _context.NewsletterComponents.Find(component.NewsletterComponentId);
to至
var dbComponent = _context.NewsletterComponents.Include(t => t.NewsletterNewPlants).FirstOrDefault(t => t.NewsletterComponentId == component.NewsletterComponentId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.