Was trying out some code with the EF “code first” method and ran into a strange problem.
My datacontext:
public class BookmarkerDataContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasKey(u => u.UserId);
base.OnModelCreating(modelBuilder);
}
}
Where the user object is:
public class User
{
public long UserId { get; set; }
public ICollection<Tag> Tags { get; set; }
}
In my code I am doing something fairly simple:
public void UpdateUserTags(User user,ICollection<Tag> taglist)
{
user.Tags = new List<Tag>(user.Tags.Union(taglist));
datacontext.Users.Add(user);
datacontext.SaveChanges();
}
The user object I am passing to this function is the result of something like:
datacontext.Users.SingleOrDefault(u => u.UserId==id)
Everytime I call the UpdateUserTags function it seems to create a new Row in the User table instead of updating it. Am I doing something wrong here?
@Donald is correct, you need to
Attachto the ObjectContext when making updates.However, that is only if your entity is detached.
If sounds like you have already retrieved the single entity from the graph:
Which means you don’t need to Attach or get it again. Just do this:
However, i wouldn’t recommend replacing the entire Tags collection, add the tags:
HTH