Reputation: 13
For example I have the following code:
Product p = new Product { Id = 5, Name = "milk" };
....
cnx.Product.Attach(p);
cnx.Entry(p).State = System.Data.EntityState.Modified;
cnx.SaveChanges();
EF generates the following query:
update Product set Name = @parameter1 where Id = @parameter2 ...
How can I force EF to add an additional check to the update query, for example :
update Product set Name = @parameter1 where Id = @parameter2 AND CategoryId = @parameter3
I'll give another example to better understand the problem:
public partial class SomeEntity
{
public int SomeEntityId { get; set; }
public string Name { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
I have an MVC application, where I store the UserId
in the session after the user logs in. In some page the user can edit SomeEntity
. Here is that method :
[HttpPost]
public EditSomeEntity(int someEntityId,string name)
{
int userId = (int)Session["UserId"];
SomeEntity updated = new SomeEntity
{ SomeEntityId = someEntityId,Name = name, UserId = userId };
var MyContext cnx = new MyContext();
cnx.SomeEntity.Attach(updated);
cnx.Entry(updated).State = System.Data.EntityState.Modified;
cnx.SaveChanges();
return View();
}
So I need that EF generates :
update SomeEntity set Name = @parameter1 where SomeEntityId = @parameter2 AND UserId = @parameter3
because SomeEntityId
came from client side it easily can be changed, so I need check that particular entity treat to particular user.
Upvotes: 1
Views: 64
Reputation: 11277
You can set the ConcurrencyMode
to Fixed
:
This will use all properties on an entity when updating.
The reason it behavive like that, is to ensure that the record only is updated if it hasn't changed.
See more here
Upvotes: 1