【问题标题】:Entity Framework POCO - Refresh a navigation property实体框架 POCO - 刷新导航属性
【发布时间】:2011-04-19 20:15:54
【问题描述】:

我在刷新相关实体集合时遇到了一些问题。

基本上问题如下:

public class Student
{
    public virtual ICollection<Lecture> Lectures { get; set; }

    public void AddLecture(Lecture lecture)
    {
        Lectures.Add(lecture);
    }

    public void CancelChanges()
    {
        _context.Refresh(RefreshMode.StoreWins, this);
        _context.LoadProperty(this, (o) => o.Lectures, 
            MergeOption.OverwriteChanges);
    }
}

public class Grade
{
    public virtual Student { get; set; }
}

现在我有了一些用于添加讲座的 GUI,如果需要,我们可以取消编辑过程:

public void ExampleEdit()
{
    Student student = _context.Students.SingleOrDefault(/* blah */);
    student.AddLecture(_context.Lectures.SingleOrDefault(/* e.g. math */));
    student.CancelChanges();
    // At this point student SHOULD have no lectures anymore since the 
    // property was loaded with overwrite changes option.
    // Yet the Lectures still contains the lecture we added there
}

那么,代码不好吗?有什么方法我使用不正确吗?是否可以完全重新加载整个对象?..

【问题讨论】:

    标签: entity-framework poco navigation-properties


    【解决方案1】:

    我认为你误解了 MergeOption.OverwriteChanges。默认情况下,只要 ObjectContext 执行查询,如果任何返回的对象已存在于缓存中,则这些对象的新返回副本将被忽略。

    请注意,这一切都基于 EntityKeys。基本上检查从查询返回的对象的 EntityKeys,如果一个对象具有 same EntityKey(在同一个 EntitySet 中,在你的情况下,Lectures) 已经存在于缓存中,现有对象保持不变。

    但是,如果您启用OverwriteChanges,那么它将替换现有实体的当前值与来自数据库的值,即使内存中的实体已被编辑。

    正如您所看到的,您正在向学生添加一个 Lecture,这对 Student 来说是全新的,并且不会被覆盖,因为它的 EntityKey 与根据您的 LoadProperty() 调用来自数据库的不同.

    一种解决方案是在 LoadProperty() 之前简单地清除学生对象中的所有 Lectures:

    public void CancelChanges() {
        _context.Refresh(RefreshMode.StoreWins, this);
        this.Lectures.Clear();
        _context.LoadProperty(this, (o) => o.Lectures, MergeOption.OverwriteChanges);
    }
    

    【讨论】:

    • 非常感谢您的解释 - 它让我的脑海中的很多事情变得更加清晰。而且您提出的解决方案非常方便 - 我刚刚更新了我的代码并且事情确实有效。
    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2016-03-29
    • 2016-05-29
    相关资源
    最近更新 更多