Add object list to DB context in Entity Framework

asp.net asp.net-mvc entity-framework entity-framework-5 entity-framework-6

Question

Here is one approach where we can add items in database context one by one for save data.

  List<AuditTrails> auditLogs= new List<AuditTrails>();

  foreach (AuditTrail a in auditLogs)
  {
      if (a.Operation == CreatedBy)
      {
         if (!string.IsNullOrEmpty(a.NewState))
             context.AuditTrails.Add(a);
      }
      else
         context.AuditTrails.Add(a);
  }
  context.SaveChanges();

Is there any way to do without Loop? I am working with Entity Framework 6. `

1
2
2/18/2015 5:24:24 PM

Accepted Answer

Also, you can use the AddRange method, but first you have to filter your collection as @ChrisPratt suggests in his answer:

var elementsToBeAdded=auditLogs.Where(a => (a.Operation == CreatedBy && !string.IsNullOrEmpty(a.NewState)) || 
                                            a.Operation != CreatedBy);
context.AuditTrails.AddRange(elementsToBeAdded);

If AutoDetectChangesEnabled is set to true (which is the default), then DetectChanges will be called once before adding any entities and will not be called again. This means that in some situations AddRange may perform significantly better than calling Add multiple times would do. Note that entities that are already in the context in some other state will have their state set to Added. AddRange is a no-op for entities that are already in the context in the Added state

2
2/18/2015 5:27:30 PM

Popular Answer

Technically, no, but you can, I think, get the gist of what you're looking for via the ForEach method of List.

auditLogs.Where(a =>
    (a.Operation == CreatedBy && !string.IsNullOrEmpty(a.NewState)) || 
    a.Operation != CreatedBy
).ToList().ForEach(a => context.AuditTrails.Add(a));


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow