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 method that allows us to add objects to the database context one at a time in order to 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 it possible to live without Loop? Working with Entity Framework 6 is what I do.

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

Accepted Answer

Additionally, you can filter your collection before using the AddRange approach, as @ChrisPratt advises in his response:

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

the value of AutoDetectChangesEnabled istrue (which is standard), after thatDetectChanges will only be used once before any entities are added, after which it will not be used again. This indicates that in some circumstancesAddRange might outperform calling by a substantial marginAdd A number of times would do. Keep in mind that things in the context that are already in another state will have their state set toAdded . AddRange for entities that are already present in the context of theAdded state

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

Popular Answer

Technically, no, however I believe you may find what you're looking for in general via theForEach manner ofList .

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