Disable Identity Entity Framework temporarily at runtime

Asked

Viewed 86 times

0

I need to synchronize 2 databases, One stays on the local machine and one on the server, I get the data I need by Api via Json, And it returns me the model with the data I need to insert.. However this data already comes with ID and I needed to keep this id, Only when I give the Add by Entity framework it inserts and assigns a new Id to the records I passed.. Example the following model:

public class Cliente{
public int Id {get;set;}
public stirng Nome {get;set;}
}

My Json returns this model like this:

cliente.Id == 1;
cliente.Nome == "TESTE";

When I give the Insert:

_ctx.Clientes.Add(cliente);
_ctx.SaveChanges();

Instead of the EF entering the record with Id 1 which is what is filled in the model, it obeys the Identity and assigns another Id to the model, Ex 2, but I need it to be 1.. I nay I can disable on model the option:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

Because when I register through the normal system I need you to generate the normal Id, only when I get the server data from the Api, I need you to save with the same ID that comes from the Server.. But I didn’t find an option to do this, without having to remove the model option

This is what I’ve tried to do:

 _ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo].Cliente] OFF");
 _ctx.SaveChanges();
 _ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo].Cliente] ON");

To disable Identity before I give Insert, however Entity assigns another id to the records I include. Would you have any way to disable Identity without having to remove the Databasegeneratedoption.Identity option from the model or inform before the Insert that only for those records should the Id be kept informed? Can someone help me

  • You have an API on the server side ?

  • I have, However the API does her job correctly, It returns me the data filled, I fill the client side model normally too, The default was to keep the ID but I managed, I will answer the question with the solution here

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.