实体框架 6:克隆除 ID 之外的对象

Entity Framework 6: Clone object except ID(实体框架 6:克隆除 ID 之外的对象)
本文介绍了实体框架 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 设置为 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 之外的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)