1

Using EF6. I'm calling a method on my context instance:

var usr = context.Get<User>("Doe");

As I've seen in debug mode, my usr variable stores a link to User class instance. And this instance has it's own ID, according to the database row ID.

Now I want to change LastName for my User:

usr.LastName="Anderson";

And after that I try to call following method, which's declared in my context class:

public TEntity InsertOrUpdate<TEntity>(TEntity entityInstance) where TEntity : BaseEntity
        {
            if (entityInstance is IChangable)
            {                    
                this.Entry<TEntity>((TEntity)entityInstance).State = EntityState.Added;
                this.SaveChanges();
                return (TEntity)newInstance;
            }
            else
                { 
                    if (entityInstance.ID == default(int))
                    {
                        this.Set<TEntity>().Add(entityInstance);
                    }
                    else
                    {
                        this.Entry<TEntity>(entityInstance).State = EntityState.Modified;
                    }
                    this.SaveChanges();
                    return entityInstance;
            }

        }

So, as far as you can see, I'm expecting the following behaviour:

If my User class implements the IChangable interface(ofcourse it does), i want to leave existing user row in table without any changes, but by the way, i want my context to add a row into the table with new ID and with new LastName. But it doesn't work. Existing row also has new value of LastName. Are there any suggestions?

klutch1991
  • 229
  • 2
  • 16

1 Answers1

1

You need to create a copy of your user and then save it into the database. The problem is that EF doesn't use ID to referencing a record but an object instantiated that rappresent the record in the database. Here you can read more about ORM, which surely explains better than me.

erikscandola
  • 2,854
  • 2
  • 17
  • 24