猿问

没有 Id 的重复实体对象

我必须复制一个实体而不是它的 Id,然后将新实体视为一个单独的对象。我的实体 ID 的设置访问器不可访问。所以我不能修改 Id 并将其设置为 null,现在我只能在数据库中执行 AddOrUpdate(基于 Id)。我不能做一个简单的添加。我需要能够复制或克隆不同的实体,所以也许通用函数可以帮助我做到这一点,但我不知道从哪里开始。有什么帮助吗?



阿波罗的战车
浏览 119回答 1
1回答

白猪掌柜的

一种选择是利用 Automapper 执行浅层克隆。Automapper 可以配置为忽略特定属性,例如 ID,或所有具有不可访问的设置器的属性:因此,给定一个实体,例如:public class SomeObject{&nbsp; &nbsp; public int SomeId { get; private set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public SomeObject(int? id = null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (id.HasValue)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SomeId = id.Value;&nbsp; &nbsp; }}您可以像这样配置映射器:&nbsp; &nbsp; &nbsp; &nbsp; var mapperConfig = new MapperConfiguration(cfg =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cfg.CreateMap<SomeObject, SomeObject>().IgnoreAllPropertiesWithAnInaccessibleSetter();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; IMapper mapper = new Mapper(mapperConfig);&nbsp; &nbsp; &nbsp; &nbsp; var test = new SomeObject(1) { Name = "Fred" }; // object we will clone.&nbsp; &nbsp; &nbsp; &nbsp; var test2 = new SomeObject(); // example of an existing "new" object to copy values into...&nbsp; &nbsp; &nbsp; &nbsp; mapper.Map(test, test2); // Copy values from first into 2nd..&nbsp; &nbsp; &nbsp; &nbsp; var test3 = mapper.Map<SomeObject>(test); // Example of letting automapper create a new clone.在这两种情况下,ID 列都没有被复制。您可能希望使用“test2”示例来利用 context.Entities.Create 为新实体创建新的跟踪代理,尽管 EF 可以很好地处理实体的新 POCO 实例,前提是将其添加到实体 DbSet。
随时随地看视频慕课网APP
我要回答