实体框架6:除ID克隆对象 [英] Entity Framework 6: Clone object except ID

查看:215
本文介绍了实体框架6:除ID克隆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVVM的程序我有一个模型类(比如为MyModel )的,我有(使用实体框架)从数据库读取一个实例。当检索对象我提出的所有数据给用户。后来的用户将被修改某些字段。结果
我要的是创建同一个对象,除了它的 ID (因为 ID 主键的和的自动递增的)。结果
所以,我怎么能解决这个?我不想逐一复制各个领域,这不是一个可靠的方法。因为也许在未来的模式可能会被修改,所以这样一来,我将不得不考虑到这一点的克隆方法。

In my MVVM program I have a Model class (say MyModel) from which I have an instance of reading from the database (using Entity Framework). When retrieving the object I'm presenting all the data to the user. Later on the user will be modifying some fields.
What I want is to create the same object except for it's ID (since that ID is the primary key and auto incremented).
So how could I approach this? I don't want to copy all fields one by one, this is not a robust approach. Because perhaps in the future the model may be modified, so this way I will have to take that into account in the cloning method.

那么,有没有复制的对象的任何优雅的方式,并在数据库中保存时,它的ID被自动再次增加? (设置ID为给我一个编译器错误,因为它的类型 INT )。

So is there any elegant way to copy the object and when saving in the database, it's ID gets auto incremented again? (Setting the ID to null gives me a compiler error, because it's of type int).

推荐答案

我注意到,没有必要进行复印。显然增加了模型的一个实例的数据库(即使该ID设置为一个已经存在于数据库中)时,实体框架插入在数据库和自动递增它是主键的新行。所以这个功能已经内置到EF。我不知道这一点,对不起结果
只是为了清楚起见这里有一个例子:

I noticed that there is no need for copying. Apparently when adding an instance of a model to the database (even if the ID is set to one that already exists in the database), Entity Framework inserts a new row in the database and auto-increments it's primary key. So this functionality is already built-in into EF. I didn't know this, sorry.
Just for clarity's sake here is an example:

using(var database = new MyDbContext()) {
    MyModel myModel = database.Where(m => m.SomeProperty == someValue);
    myModel.SomeOtherProperty = someOtherValue; //user changed a value
    database.MyModels.Add(myModel); //even though the ID of myModel exists in the database, it gets added as a new row and the ID gets auto-incremented 
    database.SaveChanges();
}

这篇关于实体框架6:除ID克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆