0
有人可以帮我解决我的问题吗?我在网上搜索了很多。但仍然无法解决它。无法用实体框架删除子元素
我使用Entity Framework 6代码优先与Microsoft SQL Server。
我的实体是这样的:
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; }
}
然后我尝试保存/在我的仓库更新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();
}
我的问题是,当我删除StockInfo
,并添加一个新的。在SQL Server中,我可以看到一个新的StockInfo
实体,而不是旧的实体。
但在CompanyInfo
表中,实体框架只是添加另一个而不删除前一个。
我做错了什么?有趣的是,CorpAction
效果很好。