Обновление существующей сущности и затем клонирование сущности (EF Core) - PullRequest
0 голосов
/ 25 апреля 2018

Я пытаюсь что-то сделать в 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();

Я сделал комментарии здесь и там, чтобы показать свое намерение и замешательство.

Это правильный подход?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...