gpt4 book ai didi

c# - 使用 EntityFramework 6 Code-First 播种期间的 IDENTITY_INSERT

转载 作者:IT王子 更新时间:2023-10-29 04:27:26 25 4
gpt4 key购买 nike

我有一个具有 Auto-identity (int) 列的实体。作为数据种子的一部分,我想在我的系统中为“标准数据”使用特定的标识符值,之后我想让数据库整理出 id 值。

到目前为止,作为插入批处理的一部分,我已经能够将 IDENTITY_INSERT 设置为 On,但 Entity Framework 不会生成包含 Id 的插入语句.这是有道理的,因为模型认为数据库应该提供值,但在这种情况下,我想提供值。

模型(伪代码):

public class ReferenceThing
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id{get;set;}
public string Name{get;set;}
}

public class Seeder
{
public void Seed (DbContext context)
{

var myThing = new ReferenceThing
{
Id = 1,
Name = "Thing with Id 1"
};

context.Set<ReferenceThing>.Add(myThing);

context.Database.Connection.Open();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT ReferenceThing ON")

context.SaveChanges(); // <-- generates SQL INSERT statement
// but without Id column value

context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT ReferenceThing OFF")
}
}

有人能提供任何见解或建议吗?

最佳答案

所以我可能已经通过生成我自己的包含 Id 列的 SQL 插入语句来解决这个问题。这感觉像是一个糟糕的 hack,但它确实有效:-/

public class Seeder
{
public void Seed (DbContext context)
{

var myThing = new ReferenceThing
{
Id = 1,
Name = "Thing with Id 1"
};

context.Set<ReferenceThing>.Add(myThing);

context.Database.Connection.Open();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT ReferenceThing ON")

// manually generate SQL & execute
context.Database.ExecuteSqlCommand("INSERT ReferenceThing (Id, Name) " +
"VALUES (@0, @1)",
myThing.Id, myThing.Name);

context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT ReferenceThing OFF")
}
}

关于c# - 使用 EntityFramework 6 Code-First 播种期间的 IDENTITY_INSERT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24265300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com