Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Insert Identity by AddOrUpdate methode in Seed Entityframework version 6.x.x [duplicate]

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.

My code is:

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" }
    );
}

but my CityId not insert and identity automaticaly inserted

My Entityframework version is 6.1.3

Update:

I change My code to:

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 ");

and the problem is not resolved.

like image 827
Morteza Avatar asked Sep 02 '25 04:09

Morteza


1 Answers

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

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 ");
like image 200
Steve Greene Avatar answered Sep 05 '25 02:09

Steve Greene