Kros-sk / Kros.KORM

Simple and fast micro-ORM framework for .NET.
MIT License
9 stars 16 forks source link

Bug: Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF #78

Open motycak opened 3 years ago

motycak commented 3 years ago

Library name and version

Description

It is not enough to define in the DatabaseConfiguration for the entity: .AutoIncrement (autoIncrementType: AutoIncrementMethodType.Identity). When adding an item. It falls: Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF

Steps To Reproduce

  1. Initialization script:

    IF NOT EXISTS (SELECT 1 FROM sysobjects WHERE NAME='Users' and xtype='U')
    BEGIN
    CREATE TABLE [dbo].[Users](
        [Id] [bigint] IDENTITY(1,1) NOT NULL,
        [Email] [nvarchar](255) NOT NULL,
    
        CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([Id] ASC)
        WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    END
  2. DatabaseConfiguration:

    public override void OnModelCreating(ModelConfigurationBuilder modelBuilder)
    {
     modelBuilder.Entity<User>()
     .HasTableName(UsersTableName)
     .HasPrimaryKey(f => f.Id)
     .AutoIncrement(autoIncrementType:AutoIncrementMethodType.Identity);
    }
  3. Entity:

    [Alias("Users")]
    public class User
    {
        /// <summary>
        /// Id.
        /// </summary>
        public long Id { get; set; }
    
        /// <summary>
        /// Email.
        /// </summary>
        public string Email { get; set; }
    }

4.Used:

var users = _database.Query<User>().AsDbSet();
users.Add( new User() { Email = "email@email.com" });
users.CommitChanges();

Actual behavior:

When I add an annotation to an id, it adds an item.

[Alias("Users")]
public class User
{
    /// <summary>
    /// Id.
    /// </summary>
   [Key(autoIncrementMethodType: AutoIncrementMethodType.Identity)]
    public long Id { get; set; }

    /// <summary>
    /// Email.
    /// </summary>
    public string Email { get; set; }
}
Burgyn commented 3 years ago

Hi @motycak,

(un)fortunately this is not a general mistake. Because I couldn't reproduce it in example. (see my demo project)

Maybe it depends on some of your other settings, or you have a problem elsewhere. Are you sure you are using the correct instance of IDatabase to which DatabaseConfigurations is configured?