EF code first - unable to update database row

I tried some code using the EF method "code first" and ran into some 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);
        }
     }

If custom object:

   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 custom object I pass to this function is the result of something like:

datacontext.Users.SingleOrDefault(u => u.UserId==id)

Each time I call the UpdateUserTags function, a new Row is created in the User table instead of updating. Am I something wrong here?

+3
source share
4 answers

@Donald is correct, you need to Attachin ObjectContext when creating updates.

However, this is only if your object is disconnected.

, :

var user = datacontext.Users.SingleOrDefault(u => u.UserId==id);

, . :

var user = datacontext.Users.SingleOrDefault(u => u.UserId==id);
user.Tags = new List<Tag>(user.Tags.Union(taglist));
context.SaveChanges();

Tags, :

user.Tags.Add(someTag);

+4

, , .

public void UpdateUserTags(User user,ICollection<Tag> taglist)
{
    datacontext.Attach(user);
    user.Tags = new List<Tag>(user.Tags.Union(taglist));
    datacontext.SaveChanges();
}

, . .

+3

datacontext.Users.Add();

, ​​ users.

, , . EF wonk, ymmv

0
source

This has nothing to do with your specific problem, but for lazy loading you want the tags to be marked as virtual

public virtual ICollection<Tag> Tags { get; set; }

Also, it looks like you are trying to add new tags for the user (or update their tags), if so, then you will want to use Attach as Donald suggested

0
source

Source: https://habr.com/ru/post/1772946/


All Articles