使用相关实体更新Entity Framework中的分离实体

时间:2013-10-11 16:04:21

标签: c# entity-framework

我正在使用VS 5在VS 2012中开发解决方案,我很困惑在添加和更新实体时指定实体关系的正确方法。

这些是我的主要课程notifierperson

public class Notifier : Person
{
    public bool IsValid { get; set; }
    public int NotifierTypeID { get; set; }
    public virtual NotifierType NotifierType { get; set; }
    public int MyCaseID { get; set; }
    public virtual MyCase MyCase { get; set; }
}

public abstract class Person
{
    public int PersonID { get; set; }
    public String Name { get; set; }        
}

通知者属于案例

public class MyCase
{
    public int MyCaseID { get; set; }        

    public DateTime DateOfNotification { get; set; }
    public virtual ICollection<Notifier> Notifiers { get; set; }        
}

并有一个类型:

public class NotifierType
{
    public int NotifierTypeID { get; set; }
    public string NotifierTypeName { get; set; }
}

我在通知程序和案例以及通知程序类型之间公开了外键。

我用来添加/更新通知程序的方法是:

using (MyContext dbContext = new MyContext(connectionString))
{

    notifier.MyCaseID = MyCaseID;
    notifier.NotifierTypeID = notifierView.NotifierTypeID;

// **** the puzzling line ****  
    notifier.NotifierType = dbContext.NotifierTypes.Find(notifierView.NotifierTypeID);

    //dbContext.Database.Log = s => System.Diagnostics.Debug.Write(s);
    dbContext.Entry(notifier).State = notifier.PersonID == 0 ? EntityState.Added : EntityState.Modified;

    dbContext.SaveChanges();

    //  save the ID in case it's new
    notifierViewReturn.PersonID = notifier.PersonID;
}

我对上面评论**** the puzzling line ****之后的界限感到困惑。我明确指定了外键,如果我要添加一个通知程序,则不需要这一行,但如果我更新对象,我确实需要它,否则会引发异常。

例外是

Message=A referential integrity constraint violation occurred: 
The property values that define the referential constraints are not 
consistent between principal and dependent objects in the relationship.

任何人都可以解释为什么需要这条线。感谢

1 个答案:

答案 0 :(得分:2)

更新现有实体时,在进行更改之前,实体已经填充了NotifierType(导航属性)和NotifierTypeID。如果您随后更改了NotifierTypeID但未更新NotifierType,则Entity Framework会检测到潜在的不一致性(NotifierTypeID!= NotifierType.NotifierTypeID)并抛出您获得的异常。这就是您需要在更新时设置两者的原因。添加时,您没有此问题,因为只定义了其中一个ID(NotifierTypeID,而不是NotifierType.NotifierTypeID),所以它只使用那个。

如果您想避免检索更新的通知程序类型,您应该只能将其设置为null,在这种情况下不会出现差异,它只能使用您设置的NotifierTypeID: / p>

notifier.MyCaseID = MyCaseID;
notifier.NotifierType = null;
notifier.NotifierTypeID = notifierView.NotifierTypeID;

希望有所帮助!

相关问题