Undo changes in entity framework entities

Query ChangeTracker of DbContext for dirty items. Set deleted items state to unchanged and added items to detached. For modified items, use original values and set current values of the entry. Finally set state of modified entry to unchanged: public void RollBack() { var context = DataContextFactory.GetDataContext(); var changedEntries = context.ChangeTracker.Entries() .Where(x => x.State != … Read more

How and where to call Database.EnsureCreated and Database.Migrate?

I think this is an important question and should be well answered! What is Database.EnsureCreated? context.Database.EnsureCreated() is new EF core method which ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created and also it ensures … Read more

How to make Entity Framework Data Context Readonly

In addition to connecting with a read-only user, there are a few other things you can do to your DbContext. public class MyReadOnlyContext : DbContext { // Use ReadOnlyConnectionString from App/Web.config public MyContext() : base(“Name=ReadOnlyConnectionString”) { } // Don’t expose Add(), Remove(), etc. public DbQuery<Customer> Customers { get { // Don’t track changes to query … Read more

Solving “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection” InvalidOperationException

By default Entity Framework uses lazy-loading for navigation properties. That’s why these properties should be marked as virtual – EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading. E.g. if you have this entity: public class MemberLoan { public string LoandProviderCode { get; set; } public virtual Membership Membership { … Read more

ASP.NET MVC: Is Controller created for every request?

A Controller is created for every request by the ControllerFactory (which by default is the DefaultControllerFactory). http://msdn.microsoft.com/en-us/library/system.web.mvc.defaultcontrollerfactory.aspx Note that the Html.Action Html Helper will create another controller. The short version is that ControllerActivator.Create is called (for every request) to create a Controller (which inits a new Controller either through the DependencyResolver or through the Activator … Read more