Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create<Object> vs new <Object> in Entity Framework

I've got an initializer/updater for an entity object. Is there any danger in using

Dim myObject As SpecialThing = New SpecialThing()

Then setting all the values (using the updater that is already written), or do I need to use:

Dim myObject As SpecialThing = SpecialThing.Create()

There are 30 parameters and the updater already sets the values/handles errors. Just looking to reuse that code.

like image 664
Tyler DeWitt Avatar asked Nov 20 '11 21:11

Tyler DeWitt


2 Answers

I don't know what exactly you mean with myDB.CreateSpecialThing(.....). I have three interpretations:

  • objectContext.CreateObject<SpecialThing>()

  • dbContext.SpecialThings.Create() (EF >= 4.1)

  • SpecialThing.Create(.....) (a static method of EntityObject derived entities)

The third method is only an autogenerated helper which takes parameters (for the required fields), sets properties and returns the object. It's exactly the same as creating the object with new and setting properties afterwards.

The first two methods come into play if you are working with POCOs and use lazy loading or change tracking proxies. These methods will create a dynamic proxy of the entity (which is a dynamic class derived from your entity class) and not directly the entity. None of these methods attach the entity to the context, you must do this manually - no matter if you use these methods to create the entity or create it with new.

Example where using CreateObject<T>/Create can be important, assuming a User entity with a virtual Roles collection:

using (var ctx = new MyDbContext())
{
    var user = ctx.Users.Create();
    user.Id = 1;
    ctx.Users.Attach(user);

    var roles = user.Roles;
}

Using virtual enables lazy loading for the Roles collection and the code above would load all roles of user 1 (or an empty collection if the user has no roles). Using new on the other hand...

using (var ctx = new MyDbContext())
{
    var user = new User { Id = 1 };
    ctx.Users.Attach(user);

    var roles = user.Roles;
}

...doesn't allow to lazily load the collection because user is not a dynamic proxy object. roles would be null, no matter if the user has roles or not.

So, I'd say that there is no danger to create an entity with new. You just have to keep in mind that you don't have the features of lazy loading or change tracking proxies for an entity created with new.

like image 75
Slauma Avatar answered Sep 18 '22 05:09

Slauma


If you create the object yourself, it won't be attached to the context. You'll need to attach the object in order to have changes update in the database.

Eventhough if you create Entity using Create Method, it will not be attached to the context and this will save in DB by SaveChanges method. http://msdn.microsoft.com/en-us/library/gg696136(v=vs.113).aspx

like image 33
Reed Copsey Avatar answered Sep 19 '22 05:09

Reed Copsey