2

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

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Suggested small improvement: auditLogs.Where(a => !(a.Operation == CreatedBy && string.IsNullOrEmpty(a.NewState));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.