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. `
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
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));