更新现有实体,然后克隆实体(EF Core)

时间:2018-04-25 20:25:34

标签: c# entity-framework-core

我正在尝试在Entity Framework Core中做一些事情 我更新现有实体,然后创建具有相同属性的复制实体。

以下是代码段:

var originalEntity = _context.Product
                .Include(x => x.Class)
                .Include(x => x.Type)
                .Include(x => x.Audit);

// change current product's expiration date to be today + 30
originalEntity.ExpirationDate = DateTime.Today.AddDays(30);

// create a new product with updated properties but everything else same as originalEntity
var newEntity = (Product) _context.Entry(originalEntity).CurrentValues.ToObject();

// make the property changes
// not sure if I have to do "newEntity.Id = 0;". Id is autogenerated via database
newEntity.ExpirationDate = DateTime.Today.AddDays(90);
newEntity.Status = "ACTIVE";
newEntity.Audit = null; // don't want to make a copy of all the audit logs which is stored in a different table... is this the proper way to do so?

// track this new entity as added? I heard this won't work in Entity Framework Core if the ID is not set to null/0. Is this true?
_context.Product.Add(newEntity);

// finally commit all the changes to DB
_context.SaveChanges();

我在这里和那里发表评论以表明我的意图和困惑。

这是正确的做法吗?

0 个答案:

没有答案