当前位置: 动力学知识库 > 问答 > 编程问答 >

entity framework - Can I query a modified object before saving its changes?

问题描述:

I am authoring a domain model that I will later map to a database using EF Code First. This is my first project using Entity Framework, and although I've read a book about it a while back, I can't remember all the details of how it works.

In one part of the domain model I have a one-to-many relationship.

public class Parent

{

public IList<Child> Children { get; private set; }

}

After the user has modified an in-memory instance of Parent, and clicks a button, then it will be time to persist that instance to the database. At that time, I must first run some domain-specific comparison logic between the instance as it exists in the database (before saving) and the unsaved modified version that's in memory. So I need to query the database to retrieve an unmodified duplicate of the Parent instance and its Children.

Does EF Code First let me safely run such a query? I just worry that when EF runs such a query it will see that each Child is already in memory and so reuse those instances, and overwrite their modifications, instead of instantiating duplicates. In this situation, I in fact want the duplicates.

网友答案:

Code first lets you access the original and changed values of a tracked object like this:

Parent parent;
...
var curVal = context.Entry(parent).Property(p => p.Property).CurrentValue;
var origVal = context.Entry(parent).Property(p => p.Property).OriginalValue;

You should also be able to do this with individual values in the Children collection

Subsequent queries will supply a new set of entities with current database values, but if you want to check the cache the context holds, that's very straightforward as described here:

http://weblogs.asp.net/ricardoperes/archive/2012/03/19/entity-framework-code-first-get-entities-from-local-cache-or-the-database.aspx

分享给朋友:
您可能感兴趣的文章:
随机阅读: