作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有一个具有 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/
根据 Android docs ,activity生命周期如下: onCreate() onStart() onResume() onPause() onStop() onDestroy() 问题是,
我有一门类(class)有很多专栏,但这个问题只需要其中三个: ---------------------------------------- | start_date | start_time
给定在同一个 Tomcat 6 上运行的两个 Web 应用程序。如果您从一个应用程序到另一个应用程序进行 http 调用,Tomcat 是否会“短路”此调用,或者它会在调用之前一直在 interweb
我是一名优秀的程序员,十分优秀!