Noël Rimbert
Noël Rimbert

Reputation: 183

Entity framework - Check if entry exists before insertion and auto-increment

I'm currently facing a minor issue regarding the process of saving data in EF. I am trying to insert or update multiple lines in a single transaction with an auto-incremented field.

Here is my code:

var Orders = ctx.Orders;
foreach (var order in ordersForm)
{
    var OrderEntity = Orders.Find(order.orderId);
    if (OrderEntity == null)
    {
        OrderEntity = new Order();
    }

    OrderEntity.Name = order.name;
    OrderEntity.Date = DateTime.Now;
    ...

    // If no order in the set --> add order
    if (!Orders.Local.Any(e => e == OrderEntity))
    {
        Orders.Add(OrderEntity);
    }
    if (ctx.Entry(Order).State == EntityState.Added 
       || ctx.Entry(Order).State == EntityState.Modified)
    {
        OrderEntity.DateModified = DateTime.Now;
        OrderEntity.LastUpdatedBy = Session["user"].ToString();
    }
    ...
}
ctx.SaveChanges();

So I am trying to get an entity from the db or the cache:

Please, note that since I didn't call the SaveChanges method my newly added entity will have an empty Id.

The problem comes up when I iterate a second time and that I have to create another object:

Here are my options:

This is the situation... I would like to know if there is any method or "pattern" which exists for this specific case or if I should aim one of the "solutions" mentioned above?


EDIT To my great misfortune, the system was made in a very questionable way...(not by me, hehe) T_T

To make it simple, there are two fields that are updated each time a change is made: updated_by and last_updated. This means that whenever you want to save data the updated_by field is different from the value in the database. So whenever you save data all objects are considered as modified since this field is updated.

That is why I need to go through a loop to update only the fields that I need (which means all the fields except the 2 mentioned).

Upvotes: 1

Views: 1330

Answers (1)

theDarse
theDarse

Reputation: 737

Out of curiosity why is where not an option? personally i would do this by splitting the update items and the add items into two lists the use add range to add all the new items at the same time.

var newitems = ordersform.Where(i=> Orders.All(ii=>ii != i);
var updateItems = ordersform.Where(i=> Orders.Any(ii=> ii==i);
updateItems.Foreach(i => {Update Item};
Orders.AddRange(newItems);
ctx.SaveChanges();

Upvotes: 2

Related Questions