开发者

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

开发者 https://www.devze.com 2023-04-12 06:22 出处:网络
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 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.CounterT开发者_运维技巧BL.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号