简体   繁体   中英

Update using Entity Framework 1 (EF1) - on saveChanges()

I am trying to increment a counter which is stored in the DB.

So this requires me to do and update using Entity Framework 1 (EF1).

I am doing something like this:

  CounterTBL OrderCounter = MyRepository.CounterTableDetails("ORDERID"); 

  Booking Booking = new Booking();

  Booking.BookingAdminID = User.ID;
  Booking.BookingStatus = 2;

  OrderCounter.CounterFLD = OrderCounter.CounterFLD + 1;

  using (var ctx = new WhygoContext())
  {
      ctx.AddToBookings(Booking);
      ctx.SaveChanges();
   }

Booking is inserted fine, but I expected the existing record to be updated, which is was not.

A search around StackOverflow and the web shows that I should do something like this: ctx.CounterTBL.Attach(OrderCounter); ctx.ApplyCurrentValues("CounterTBLs", OrderCounter);

Or similar, but my intellisense doesn't like this and it doesn't build so I assume these are only a part of EF 4.

I am sadly stuck with EF 1. Is there a way to do this.

I'm pretty new to this stuff, so maybe I'm not going about this in the right way...

When you're inserting Booking you are creating a new instance of the context and call save changes only on that instance. Your OrderCounter was loaded from repository and I guess it used different context instance. You should share the context instance between both operations or you will have to call SaveChanges on both context.

Btw. your code is not very reliable if it is run in ASP.NET because concurrent clients can store the same counter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM