我是实体框架代码的新手,所以我想问以下问题:我有这个实体:
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,这是删除的代码:
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
表和列表中删除实体。有人可以解释为什么错误和/或如何实现我的预期目的吗?