简体   繁体   中英

How to add new row to table, using existing row data in EF6?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM