Home > Mobile >  How to create entity with foreign keys in ef core and avoid IDENTITY_INSERT error
How to create entity with foreign keys in ef core and avoid IDENTITY_INSERT error

Time:09-01

I have entity with foreign keys Project:

public class Project : IEntity
{
    public int Id { get; set; }

    public int? TypeId { get; set; }
    public virtual Type? Type { get; set; } = null!;

    // other properties...
}

I want to create a new object (insert a new entity into the database):

await Context.Set<TEntity>().AddAsync(entity);

And I have the following problem:

Microsoft.Data.SqlClient.SqlException (0x80131904): It is not possible to insert an explicit value for the identifiers column in the "Types" table when the IDENTITY_INSERT parameter is set to OFF.

So, when trying to execute this SQL query, I have an exception:

SET NOCOUNT ON;
INSERT INTO [Types] ([Id], [Name])
VALUES (@p0, @p1);

There's no need to create a new Type in the Types table. How can I fix this? I understand that I can set IDENTITY_INSERT to OFF, but I think this isn't a good practice.

CodePudding user response:

you can disable the identity using data annotions or fluent api.

solution 1: data annotions

public class Type: IEntity
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    // other properties...
}

solution 2 : fluent api

modelBuilder.Entity<Type>()
        .Property(b => b.Id)
        .ValueGeneratedNever();

CodePudding user response:

Have you tried to execute an SQL query?

SET IDENTITY_INSERT Types ON;

INSERT INTO Types ([Id], [Name])
VALUES ...

SET IDENTITY_INSERT Types OFF;

Can you share an example of your SQL schema?

I think you need to configure the relationship as optional Required and optional relationships either via the fluent API, or with an explicit Nullable<> foreign key property

  • Related