开发者

How to update Entity but insert new row on SaveChanges?

I have Entity1 with properties

Entity1.id= 1;
Entity1.a = 10;
Entity1.b = 123;
Entity1.c = 231;

I wan't to change properti开发者_运维技巧es but to insert a new row on context.SaveChanges() not to do update for existing id. I tried to set Entity1.entityKey = null but it fails.

Any ideas?

Thanks.


Set the EntityState to Added in the ObjectStateManager:

var Entity1 = context.YourEntities.Where(e => e.Id == 1).FirstOrDefault();

ObjectStateEntry osmEntry = context.ObjectStateManager.GetObjectStateEntry(Entity1);
osmEntry.ChangeState(EntityState.Added);

context.SaveChanges();

That is if your entity is already attached to the context (e.g. if you fetched it before).

This will 'copy' the entity with Id = 1 unless you make any changes to the properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜