سؤال

I am trying to get a better understanding of System.Data.Entity.DbContext.

1) For persisting data, the class only has a SaveChanges method. Does that mean changes only to a specific record cannot happen?

2) If the data in the database is changed (by another application), how does the context get up-to-date information? Is this handled automatically, or is the data late binding? I don't see any kind of Refresh method.

Any useful references on this is also appreciated.

هل كانت مفيدة؟

المحلول

Does that mean changes only to a specific record cannot happen?

Yes, this is true AFAIK. But you can create multiple DbContext instances without any problem.

If the data in the database is changed (by another application), how does the context get up-to-date information?

The data is not loaded when the context is constructed but when it is requested:

using(var db = new MyDbContext())
{
    var items = db.MyItems.Where(i => i.Something == true);
    var list = items.ToList(); // <= here the DB is queried
}

items will be a IQueryable<MyItem> object and as long as you keep it a IQueryable the DB is not actually queried. Meaning you can add additional Where or OrderBy without DB-access. As soon as you convert it to IEnumerable (e.g. with the ToList from my example) or execute some specific methods (like e.g. First) the DB will be queried.

نصائح أخرى

1) SaveChanges saves all unsaved changes, that are 'visible' by current DbContext (changes to entities loaded from this dbcontext, new entities added to DbSets of this dbContext, entities 'attached' to this context via dbContext.Entry(someObject).State = ...).

If you want save only one entity - you must not change other entities, or have different dbContext, or play with State. Last two are "strange", so just change you code so it doesn't touch entities you don't want to save. For example, do not add new objects via Add (hold then in separate variables). Also, there is a AsNoTracking method in DbSet that detaches loaded objects once they read and you can freely change them - DbContext will not track this entities and will not "see" this changes.

2) There is a Reload method for already loaded entity: dbContext.Entry(someObject).Reload()

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top