0

Through examples in the past, I have learned to use DbSet<TEntity>.Create() to create entity objects for insertion. However, I have found just using the default constructor with an object initializer seems to work just as well.

My main question is, do we ever still need to use DbSet<TEntity>.Create(), and why?

Bonus question: What, if any, is the functional difference between these two code examples?

"By the book":

    Dim db As New EFDAL.WidgetDbEntities()
    Dim dbWidgetBatch2 As EFDAL.WidgetBatch = db.WidgetBatches.Create()
    dbWidgetBatch2.CreationTimestamp = Now
    dbWidgetBatch2.CreatedByUsername = userName
    db.WidgetBatches.Add(dbWidgetBatch2)
    db.SaveChanges()

"Works just as well?":

    Dim db As New EFDAL.WidgetDbEntities()
    Dim dbWidgetBatch As New EFDAL.WidgetBatch With {
        .CreationTimestamp = Now,
        .CreatedByUsername = userName
    }
    db.WidgetBatches.Add(dbWidgetBatch)
    db.SaveChanges()
Maess
  • 4,118
  • 20
  • 29
pseudocoder
  • 4,314
  • 2
  • 25
  • 40

1 Answers1

0

After reviewing the duplicate candidate, I see the main subject matter of this question has already been covered. However I feel it's worthwhile to summarize how the concepts apply to my question.

If I understand correctly, the short answer is that DbSet.Create() creates a "proxied" object which enables, among other things, lazy loading of navigation properties.

In the examples I posted, no navigation properties were used so both examples do in fact work equivalently, and for most inserts I suspect most people will not need a proxied object.

Links:

pseudocoder
  • 4,314
  • 2
  • 25
  • 40
  • An alternative to using `DbSet.Create()` is using `Entry(model).Reference(o => MyRef).Load()` after `model` has been added to the DB context. For example: if `model.MyRefId` has a value then the corresponding entity of `model.MyRef` will be loaded. I find this useful when working with ASP.NET MVC applications and the out-of-the-box model binder. – Jeremy Cook May 13 '14 at 13:52