[英]Can't delete child element with Entity Framework
Can someone please help me with my problem? 有人可以帮我解决我的问题吗? I searched on the internet a lot.
我在互联网上搜索了很多。 But still can't solve it.
但仍然无法解决。
I'm using Entity Framework 6 code-first with Microsoft SQL Server. 我将Microsoft SQL Server与Entity Framework 6一起使用。
My entities are like this: 我的实体是这样的:
public class StockInfo
{
[JsonIgnore]
[Key]
public int StockInfoID { get; set; }
[ForeignKey("StockInfoID")]
public virtual CompanyInfo companyInfo { get; set; }
[ForeignKey("StockInfo_ID")]
public virtual List<CorpAction> corpActions { get; set; }
...... so on
}
public class CompanyInfo
{
[JsonIgnore]
// [Key, ForeignKey("StockInfo")]
public int CompanyInfoID { get; set; }
public int avgVolume { get; set; }
public string coName { get; set; }
...........
}
public class CorpAction
{
public int ID { get; set; }
public int corpActionType { get; set; }
public string date { get; set; }
........
public int StockInfo_ID { get; set; }
}
Then I try to save/update StockInfo
in my repository: 然后,我尝试在存储库中保存/更新
StockInfo
:
public void SaveStockInfo(StockInfo StockWeeklyInfo)
{
var content = context.StockInformation.Where(x => x.companyInfo.symbol == StockWeeklyInfo.companyInfo.symbol).FirstOrDefault();
if (content == null)
{
context.StockInformation.Add(StockWeeklyInfo);
}
else
{
context.StockInformation.Remove(content);
context.Entry(content).State = EntityState.Deleted;
context.StockInformation.Add(StockWeeklyInfo);
}
context.SaveChanges();
}
My problem is that when I remove StockInfo
and add a new one. 我的问题是,当我删除
StockInfo
并添加一个新的时。 In SQL Server, I can see a new StockInfo
entity instead of the old one. 在SQL Server中,我可以看到一个新的
StockInfo
实体,而不是旧的。
But in the CompanyInfo
table, Entity Framework just add another one and doesn't delete the previous. 但是在
CompanyInfo
表中,实体框架仅添加了另一个,而不删除前一个。
What I am doing wrong? 我做错了什么? Interestingly,
CorpAction
works well. 有趣的是,
CorpAction
运作良好。
First of all - your code first model looks odd. 首先-您的代码优先模型看起来很奇怪。 You have:
你有:
[ForeignKey("StockInfoID")]
public virtual CompanyInfo companyInfo { get; set; }
and 和
[ForeignKey("StockInfo_ID")]
public virtual List<CorpAction> corpActions { get; set; }
Are those navigations declared properly? 这些导航是否正确声明? I doubt it, that you CompanyInfo entity has the same Id as StockInfo.
我怀疑您的CompanyInfo实体具有与StockInfo相同的ID。
You also expect CompanyInfo to be deleted when StockInfo is deleted. 您还希望删除StockInfo时删除CompanyInfo。 Was the foreign key declared as "ON DELETE CASCADE"?
外键是否声明为“ ON DELETE CASCADE”?
Please double check this and if it does not help please create "Create a Minimal, Complete, and Verifiable example" and we will try to help : 请仔细检查,如果没有帮助,请创建“创建一个最小,完整和可验证的示例”,我们将尽力帮助您:
https://stackoverflow.com/help/mcve https://stackoverflow.com/help/mcve
Please add then your database model as well. 请同时添加您的数据库模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.