简体   繁体   English

如何使用EF6中的现有行数据向表中添加新行?

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

Using EF6. 使用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. 正如我在调试模式下看到的那样,我的usr变量存储了指向User类实例的链接。 And this instance has it's own ID, according to the database row ID. 根据数据库行ID,此实例具有其自己的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 . 如果我的User类实现了IChangable接口(当然是这样),那么我想保留表中的现有用户行,而不进行任何更改,但是,顺便说一句,我希望我的上下文在表中添加具有新ID和新LastName的行 But it doesn't work. 但这是行不通的。 Existing row also has new value of LastName . 现有行还具有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. 问题在于EF不使用ID来引用记录,而是实例化了一个表示数据库中记录的对象。 Here you can read more about ORM, which surely explains better than me. 在这里,您可以阅读有关ORM的更多信息,它肯定比我解释得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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