views:

237

answers:

2

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.

+1  A: 

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();
}
xxx
+1  A: 

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

TheCloudlessSky
Gotcha, thanks for the tip. The only issue with this is I am using MVC, and would like to take advantage of model binding. In your example, I would need to call the repo.GetForUpdate then UpdateModel and then Save. But it is good to know there are alternatives.
xxx
Sorry, can't upvote your question (not enough rep)
xxx
@xxx - No worries.
TheCloudlessSky