无法删除具有Entity Framework的子元素

时间:2017-08-04 08:44:36

标签: c# entity-framework

有人可以帮我解决我的问题吗?我在互联网上搜索了很多。但仍然无法解决它。

我使用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效果很好。

1 个答案:

答案 0 :(得分:0)

首先 - 你的代码第一个模型看起来很奇怪。你有:

  [ForeignKey("StockInfoID")]
  public virtual CompanyInfo companyInfo { get; set; }

[ForeignKey("StockInfo_ID")]
public virtual List<CorpAction> corpActions { get; set; }

这些导航是否正确宣布?我怀疑,您的CompanyInfo实体与StockInfo具有相同的ID。

您还希望在删除StockInfo时删除CompanyInfo。外键是否被声明为&#34; ON DELETE CASCADE&#34;?

请仔细检查一下,如果没有帮助,请创建&#34;创建一个最小,完整且可验证的示例&#34;我们会尽力帮助:

https://stackoverflow.com/help/mcve

请添加您的数据库模型。