简体   繁体   English

使用Entity Framework 1(EF1)更新-在saveChanges()上

[英]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). 因此,这需要我使用实体框架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); 在StackOverflow和网上进行的搜索显示,我应该执行以下操作:ctx.CounterTBL.Attach(OrderCounter); ctx.ApplyCurrentValues("CounterTBLs", 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. 或类似,但是我的智商不喜欢它并且它没有构建,因此我认为这些只是EF 4的一部分。

I am sadly stuck with EF 1. Is there a way to do this. 可悲的是,我陷入了EF1。有没有办法做到这一点。

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. 插入Booking您正在创建上下文的新实例,并仅在该实例上调用保存更改。 Your OrderCounter was loaded from repository and I guess it used different context instance. 您的OrderCounter是从存储库加载的,我猜它使用了不同的上下文实例。 You should share the context instance between both operations or you will have to call SaveChanges on both context. 您应该在两个操作之间共享上下文实例,否则您将不得不在两个上下文上调用SaveChanges

Btw. 顺便说一句。 your code is not very reliable if it is run in ASP.NET because concurrent clients can store the same counter. 如果代码在ASP.NET中运行,则代码不是很可靠,因为并发客户端可以存储相同的计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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