Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update EF 4 Feature CTP 4 Detached POCO

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.

like image 383
xxx Avatar asked Aug 06 '10 16:08

xxx


2 Answers

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();
}
like image 95
xxx Avatar answered Nov 15 '22 10:11

xxx


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

like image 32
TheCloudlessSky Avatar answered Nov 15 '22 11:11

TheCloudlessSky