EntityFramework DatabaseGenerated

0

I have a property in my model where it automatically generates the Id when it is inserted in Db, but I have a specific case where I need to put the Id manually, is there any way to prevent EF from generating the automatic Id if I create and send the object with the fixed Id ignores it and generates a new one.

My question is: Is it possible to save an option to bypass automatic generation? In a specific case I need this, in the others the generation should be automatic as is the code below. Just to clarify, the problem is in the database Seed, where I need to add a user with fixed Id where it is related to the properties and other relationships of another system, in the others will be generated automatically therefore: I can not remove this automatic ID generation property.

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override Guid Id
    {
        get => base.Id;
        set => base.Id = value;
    }
    
asked by anonymous 12.09.2017 / 16:11

1 answer

1

What you should do is enable the ability to enter explicit values in the identity column of your table. This is done by the

SET IDENTITY_INSERT [TABELA] {ON|OFF}

Imagine we have the following template:

public class Blog {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int BlogId { get; set; }
    public string Titulo { get; set; }
}

The excerpt of the method that inserts into your bank should look like this:

if (blog.Titulo == tituloDeterminado) {
    using (var transaction = _context.Database.BeginTransaction()) {
        blog.BlogId = valorDeterminado;
        _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Blog] ON");
        _context.SaveChanges();
        _context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Blog] OFF");
        transaction.Commit();
    }
}
else {
    await _context.SaveChangesAsync();
}

The code snippet will assign a given valor (variable valorDeterminado ) whenever titulo is equal to a certain value ( tituloDeterminado ).

Understand this as an example and not as a final solution for your project. Adapt it according to your needs.

Source:

  

link

    
15.09.2017 / 20:20