问题描述
在我的 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 设置为 null
会给我一个编译器错误,因为它的类型是 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 设置为数据库中已经存在的 ID),Entity Framework 会在数据库中插入一个新行并自动增加它的主键.所以这个功能已经内置在 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.FirstOrDefault(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 之外的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!