DbContext discard changes without disposing

public void RejectChanges() { foreach (var entry in ChangeTracker.Entries()) { switch (entry.State) { case EntityState.Modified: case EntityState.Deleted: entry.State = EntityState.Modified; //Revert changes made to deleted entity. entry.State = EntityState.Unchanged; break; case EntityState.Added: entry.State = EntityState.Detached; break; } } } Update: Some users suggest to add .ToList() to avoid ‘collection was modified’ exception. But I believe … Read more

Configure multiple database Entity Framework 6

It’s not important that how many DbContexts you have(In entity framework 6). Just put connection strings in appConfig or webConfig of startup project. Then you’re ready to go. Example of appConfig with two connectionString with Ef 6.01 & Sql Compact 4.0 <configSections> <section name=”entityFramework” type=”System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ requirePermission=”false” /> </configSections> <connectionStrings> <add name=”MainDb” … Read more

DbSet.Find method ridiculously slow compared to .SingleOrDefault on ID

Find calls DetectChanges internally, SingleOrDefault (or generally any query) doesn’t. DetectChanges is an expensive operation, so that’s the reason why Find is slower (but it might become faster if the entity is already loaded into the context because Find would not run a query but just return the loaded entity). If you want to use … Read more

Mocking EF DbContext with Moq

I managed to solve it by creating a FakeDbSet<T> class that implements IDbSet<T> public class FakeDbSet<T> : IDbSet<T> where T : class { ObservableCollection<T> _data; IQueryable _query; public FakeDbSet() { _data = new ObservableCollection<T>(); _query = _data.AsQueryable(); } public virtual T Find(params object[] keyValues) { throw new NotImplementedException(“Derive from FakeDbSet<T> and override Find”); } public … Read more

Why re-initiate the DbContext when using the Entity Framework?

Managing Lifetime You’re correct that a single static instance of DbContext is usually not recommended: The more you use an ObjectContext, generally the bigger it gets. This is because it holds a reference to all the Entities it has ever known about, essentially whatever you have queried, added or attached. So you should reconsider sharing … Read more

Entity Framework 5 deep copy/clone of an entity

One cheap easy way of cloning an entity is to do something like this: var originalEntity = Context.MySet.AsNoTracking() .FirstOrDefault(e => e.Id == 1); Context.MySet.Add(originalEntity); Context.SaveChanges(); the trick here is AsNoTracking() – when you load an entity like this, your context do not know about it and when you call SaveChanges, it will treat it like … Read more