级联删除EF代码优先

时间:2012-08-22 18:28:13

标签: entity-framework code-first

我首先使用实体​​框架代码,所以我想问下列内容: 我有这个实体:

public class ConfigurationSetEntity
{
   public virtual List<IsapreEntity> Isapres { get; set; }
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.None)]
   public virtual string Culture { get; set; }
}

还有这个:

public class IsapreEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Required]
    public virtual string IsapreName { get; set; }

    [ForeignKey("IsapreOf")]
    [Required]
    public virtual string CultureId { get; set; }

    public virtual ConfigurationSetEntity IsapreOf { get; set; }
}

当我使用ConfigurationSetEntity.Isapres.Remove(entity)时,我得到一个DbEntityValidationException,这是remove的代码:

IsapreModel original = this.ChangeSet.GetOriginal(currentIsapre);
ConfigurationSetEntity defaultConfigSet = dbContext.ConfigurationSets.Find(Constants.DefaultConfigurationSetId);
IsapreEntity originalEntity =defaultConfigSet.Isapres.Find(e => e.IsapreName==original.Isapre);
defaultConfigSet.Isapres.Remove(originalEntity);

try
{
    dbContext.SaveChanges();
}
catch (Exception ex)
{
  //This is where I catch the exception
}
defaultConfigSet.Isapres.Add(new IsapreEntity { IsapreName = currentIsapre.Isapre });
try
{
    dbContext.SaveChanges();
}
catch (Exception ex)
{
}    

这是例外:

"The IsapreOf field is required."

我想要做的是使用ConfigurationSetEntity.Isapres.Remove(entity)并从IsapreEntities表和列表中删除实体。 有人可以解释为什么错误和/或我如何实现我的预期目的?

0 个答案:

没有答案