Is it possible to get Entity Framework to recognize objects that have been created and not yet saved in database?

独自空忆成欢 提交于 2019-12-12 08:14:33

问题


Say Table1 is a table with two columns. Table1ID and Name.

If I do the following code...

var Obj1 = new Table1();
Obj1.Name = "hello"
TestDBEntities.AddToTable1(Obj1);

var currObj = Table1.Where(o => o.Name.Contains("hello")).FirstOrDefault();

currObj will return null.

But if I do this

var Obj1 = new Table1();
Obj1.Name = "hello"
TestDBEntities.AddToTable1(Obj1);
**TestDBEntitles.SaveChanges();**

var currObj = Table1.Where(o => o.Name.Contains("hello")).FirstOrDefault();

Then currObj will return the first object I created. This is because that object is in the database.

I'm creating a large batch process and I don't want to save everything to the database until the end. However, I have to do checks like make sure a certain object hasn't already been added etc. which require me to reference these objects before they have been saved to the database.

Is it possible to make LINQ queries in Entity Framework that can be aware of objects that are in memory which have not been saved to database.


回答1:


Add the created and unsaved objects to a List<T> then filter that list with linq like you did above.

EDIT: actually, i stand corrected. It looks like you can specify merge options on the ObjectContext.

TestDBEntities.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
    .Where(o => o.GetType() == typeof(Object1Type) 
           && o => o.Name.Contains("hello"))
    .FirstOrDefault();

the docs.




回答2:


I'm a bit late here... @DavidWicks answer doesn't tell the whole story!

The context does provide a mechanism to query - and it got a lot easier in EF4.1 than 4.0

In 4.1 take a look at http://msdn.microsoft.com/en-us/library/gg696248(v=vs.103).aspx the dbSet.Local property holds all of the local changes for objects (that have not been deleted) in the context, so querying against that is all you need!




回答3:


That is only what do you need to do:

    Datacontext.YourTable.Add(entity);
    var x=Datacontext.YourTable.Local;

With .Local get the local state of the entity dbset :)



来源:https://stackoverflow.com/questions/6400064/is-it-possible-to-get-entity-framework-to-recognize-objects-that-have-been-creat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!