Entity Framework new object vs DbSet.Create

449 Views Asked by At

We are migrating a web application from EF 4.0 to EF 6. The entities were earlier based on ObjectContext, but now we are looking at DBContext. The code heavily depends on lazy loading. Entities are added using following syntax:

var user = new EntityModel.User();
user.DepratmentId=25;
context.Users.Add(user);
context.SaveChanges();

var name = user.Department.Name;

the original code would easily assign department name into variable name. After Entity framework upgrade to EF6 with DBContext, user.Department is null. I understand that when we are using DBContext, Lazy Loading works only with Proxies. It would work fine if the code was changed to following:

    var user = context.Users.Create();
    user.DepratmentId=25;
    context.Users.Add(user);
    context.SaveChanges();
var name = user.Department.Name;

Problem at my hand is that we can not make this change in the whole code base. Given the large volume of code, this is practically impossible. Does someone have a solution to this?

1

There are 1 best solutions below

0
Steve Py On

Provided your entities are easily identifiable such as all being pulled from the namespace "EntityModel" then VS's Find & Replace can help with the transition. Ultimately you're going to have to eat the cost of that technical debt. Re-factoring isn't free, but the benefit from making improvements (beyond just upgrading a dependency version) should outweigh that cost.

Using Find & Replace:

Find: = new EntityModel.(?<class>.*)\(\) Replace: = context.${class}s.Create()

This will find instances like:

var user = new EntityModel.User(); and replace it with var user = context.Users.Create();

a test with:

var user = new EntityModel.User();
var test = new EntityModel.Test();
var fudge = new EntityModel.Fudge();

resulted in:

var user = context.Users.Create();
var test = context.Tests.Create();
var fudge = context.Fudges.Create();

Now this will extract the class name and pluralize it with an 's' which likely won't match 100% of the entity DBSet names, but those are easily found and corrected. The expressions can be tuned to suit differences through the application and I would recommend performing the operation on a file by file, or at most project by project basis.

An caveat is to make sure you're running with source control so that any bad attempts at a replace can be rolled back safely.