views:

160

answers:

2

I have this code:

    Message message = new Message();
    message.Id = 5;
    message.EntityKey = context.CreateEntityKey("MessageSet", entity);
    message.Votes++;
    context.Attach(entity);
    context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey).SetModifiedProperty("Votes");
    Save();

But of course, Votes initialize with 0.

How can a generated something like

Update Messages set Votes=Votes+1 where Id = 5

?? Thx

A: 

I don't think you can achieve this directly, however, you could use some Import Functions and use an SP to do what you need.

Paulo Santos
+1  A: 

As LINQ to Entities is an OR mapper, the general idea is that you would first query for the entity or entities you need to update, update them with objects in code, and issue an Update command on the ObjectContext to persist the changes to those entities. It is a key thing, but often hard to grasp early on, but the reason for using an ORM like Entity Framework, NHibernate, LINQ to SQL, etc. is to eliminate the need to write SQL, and use objects instead.

The following should be what you need:

Message msg = context.Messages.First(m => m.Id == 5);
msg.Votes += 1;

context.SaveChanges();

The call to SaveChanges will generate SQL CUD statements for you, one for each update, insert, and/or delete.

jrista
Yes, the answer would solve the problem that specified, however, it could potentially fail when dealing with concurrent users refreshing the same information.
Paulo Santos
Yes, but I dont want to do a Select =/
Fujiy