实体框架 - 使用外键删除对象,保留父项 [英] Entity Framework - Remove object with foreign key, preserving parent
本文介绍了实体框架 - 使用外键删除对象,保留父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型:
public class Company
{
//Primary key
public string ID { get; set; }
//Foreign key
public int? LogotypeID { get; set; }
}
和
public class Logotype
{
//Primary key
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? ID { get; set; }
//Foreign key
public string CompanyID { get; set; }
}
如何从公司表格中删除标识, 删除公司行?
How do I delete the logotype from the Company table, without removing the company row?
使用:
http://msdn.microsoft.com/en-us/library/system.data.entity .dbset.remove(v = vs.113).aspx
DbSet.Remove(Logotype)有以下异常:
Using:
http://msdn.microsoft.com/en-us/library/system.data.entity.dbset.remove(v=vs.113).aspx
DbSet.Remove(Logotype) thows the following exception:
{"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Companies_dbo.Logotypes_LogotypeID\". The conflict occurred in database \"ShipReg\", table \"dbo.Companies\", column 'LogotypeID'.\r\nThe statement has been terminated."}
任何想法?
Br,
Tim
Br, Tim
推荐答案
添加公司中的虚拟财产如
add a virtual property in company like
public class Company
{
//Primary key
public string ID { get; set; }
//Foreign key
public int? LogotypeID { get; set; }
public virtual Logotype Logotype {get;set;}
}
然后
dbContext.Entry<Company>(company).State=EntityState.Modified;
dbContext.Entry<Logotype>(company.Logotype).State=EntityState.Deleted;
这篇关于实体框架 - 使用外键删除对象,保留父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文