如何通过种子中的AddOrUpdate方法插入标识 [英] How to Insert Identity by AddOrUpdate methode in Seed

查看:416
本文介绍了如何通过种子中的AddOrUpdate方法插入标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有标识列的实体.作为数据种子的一部分,我想对系统中的标准数据"使用特定的标识符值. 我不想禁用身份. 我只想在迁移种子中将IDENTITY_INSERT设置为ON.

I have an entity that has an identity column. As part of the data-seed I want to use specific identifier values for the "standard data" in my system. I dont want disable identity. only i want to set IDENTITY_INSERT ON in migration seed.

我的代码是:

protected override void Seed(DelphyWCFTestService.Model.DataContext context)
{
    context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] On ");
    context.Cities.AddOrUpdate(
        p => p.CityId,
        new City { CityId = 1, Title = "Paris" }
    );
}

但是我的CityId不会插入,并且身份会自动插入

but my CityId not insert and identity automaticaly inserted

我的Entityframework版本是6.1.3

My Entityframework version is 6.1.3

更新:

我将代码更改为:

context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] On ");
var cities = new List<City>
{
    new City { CityId = 1, Title = "Paris" }
};
context.Cities.AddRange(cities);
context.SaveChanges();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] Off ");

问题没有解决.

推荐答案

AddOrUpdate不像标准LINQ那样简单(

AddOrUpdate isn't as straightforward as standard LINQ (see here).

我只会使用标准的LINQ:

I would just use standard LINQ:

if (!context.Cities.Any())
{
  using (var transaction = context.Database.BeginTransaction())
  {        var cities = new List<City> 
    {
       new City { CityId = 1, Title = "Paris" },
       new City { CityId = 2, Title = "London" },
       ...
       new City { CityId = 99, Title = "Rome" }
    }
    context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] On ");
    context.Cities.AddRange(cities);
    context.SaveChanges();
    context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] Off ");

    transaction.Commit();
  }
}

如果要添加到现有城市,则可以一个一个地测试:

If you are adding to existing cities, you could just test one by one:

if (!context.Cities.Any(c => c.CityId == 1))
{
    context.Cities.Add(new City { CityId = 1, Title = "Paris" });
}
... repeat for all cities 
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] On ");
context.SaveChanges();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Cities] Off ");

这篇关于如何通过种子中的AddOrUpdate方法插入标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆