I am trying to update a detached POCO w/ EF 4 CTP 4.
My domain class looks like this:
public class User {
public int Id { get; set; }
[Required, DisplayName("First Name")]
public string FirstName { get; set; }
[Required, DisplayName("Last Name")]
public string LastName { get; set; }
[ConcurrencyCheckAttribute, Timestamp]
public byte[] DataVersion { get; set; }
}
In the repository I have the following:
public void SaveUser(User user) {
if (user.Id > 0) {
dbContext.Users.Attach(user);
}
else {
dbContext.Users.Add(user);
}
dbContext.SaveChanges();
}
dbContext inherits from DbContext.
I am able to do inserts fine, but the attach doesn't work. I run Sql Profiler, and no sql is sent for the update.
I got it figured out....
In the dbContext class I added a method that marks the entity as modified.
public void MarkAsModified(object entity) {
base.ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
My repository method now looks like this
public void SaveUser(User user) {
if (user.Id > 0) {
dbContext.Users.Attach(user);
dbContext.MarkAsModified(user);
}
else {
dbContext.Users.Add(user);
}
dbContext.SaveChanges();
}
I know this is basically doing the same thing, but what I've done is in your User Repository have a method called GetForUpdate
or something similar:
public User GetForUpdate(int id)
{
var u = new User();
u.Id = id;
dbContext.Users.Attach(u);
return u;
}
Then when you want to "update" a user with a known id:
var user = userRepo.GetForUpdate(id);
user.Name = "John Doe";
user.Username = "john.doe";
userRepo.SaveUser(user);
Attaching the user and then modifying properties will automatically set the EntityState
as Modified
.
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With