实体框架覆盖DatabaseGeneratedOption.Identity [英] Entity Framework override DatabaseGeneratedOption.Identity
本文介绍了实体框架覆盖DatabaseGeneratedOption.Identity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有 DatabaseGeneratedOption.Identity
的模型,但是在特定情况下,想保存一个具有特定主键值的实体;
即强制 id = 1
I have a model with DatabaseGeneratedOption.Identity
, but in a specific situation, would like to save an entity with a specific value for primary key;
ie force id = 1
如果我只是分配值并保存,则ID会被自动生成的值。
If I just assign the value and save, the id gets overwritten by the auto-generated value.
var model = new User {Id = 1};
dbContext.SaveChanges();
Asser.AreEqual(1, model.Id); // false
推荐答案
您可以在保存之前设置身份插入更改。
you can set identity insert on before save change. This is sample.
var model = new User {Id = 1};
dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] ON");
dbContext.SaveChanges();
dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
Asser.AreEqual(1, model.Id);
用您的用户表名称替换[dbo]。[User]。
Replace [dbo].[User] with the name of your user table.
这篇关于实体框架覆盖DatabaseGeneratedOption.Identity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文