Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework CTP5 DbContext T4 Template "virtual" keyword

The DbContext T4 template that comes with CTP5 does not have association fixup and not all properties are marked as virtual. Does it mean it does not support ChangeTracking when disconnected from context? First of all, does it support ChangeTracking even when tracked by Context (through dynamic proxies)? I see that the requirement for change tracking is that all properties should be marked as virtual.

Are we losing any functionality using DbContext generator compared to EF4 POCO generator?

Any response is greatly appreciated.

like image 668
learner Avatar asked Feb 11 '11 02:02

learner


2 Answers

Its all about eager and lazy loading. Have a look at this

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

    public class Person
    {
        public int Id { get; set; }
        public virtual Address Address { get; set; }
        // ...
    }

    public class Address
    {
        public int Id { get; set; }
        public string AddressLine1 { get; set; }
        // ...
    }

    static void Main(string[] args)
    {
        MyDatabaseContext db = new MyDatabaseContext();
        Person person = db.Persons.Where(x => x.Id == 1).First();
        // person.Address is loaded if the propertie Address, class Person 
        // is marked as virtual. If NOT its null.
    }
like image 178
dknaack Avatar answered Nov 03 '22 06:11

dknaack


I think the classes that are generated using the DbContext Generator will only use "lazy loading proxies" and not "change tracking proxies" (note there are two types of proxies) as is described at http://blogs.msdn.com/b/adonet/archive/2009/12/22/poco-proxies-part-1.aspx. As you pointed out, all the mapped properties have to be virtual for change tracking proxies to work. This isn't required for just lazy loading proxies (where only the navigation properties have to be virtual).

I think Microsoft should change this in the T4 template because without change tracking proxies, it's a lot slower. Especially if you have a lot of entities in the object context.

I was able to confirm this. In the book Programming Entity Framework: DbContext, on page 66 it talks about this. You can use code similar to the following to verify that an object is using a change tracking proxy.

Person p = context.People.Find(123);
bool b = p is IEntityWithChangeTracker;

I'm surprised that the T4 template doesn't make all the properties virtual by default. It seems like a strange oversight unless there is a reason that they did it intentionally for some reason.

like image 44
Jon Miller Avatar answered Nov 03 '22 06:11

Jon Miller