nhibernate mapping by code identity not insert

I'm using nhibernate 5,1,1. Mapping by code when you add an entry, you send 2 requests

select max (id) From Bred

insert Into Bred (Id, Name, PetType) valuses ({value of max (id)}, text, 1)

I need the field id not to be sent in the insert request and there was no first request. Id auto increment How can I do that?

public abstract class BaseEntity
{
    /// <summary>
    /// Ин.
    /// </summary>
    public virtual int Id { get; set; }

    /// <summary>
    /// Дата добавления
    /// </summary>
    public virtual DateTime DateInsert { get; set; }
}    

public abstract class BaseMapping<T> : ClassMapping<T> where T : BaseEntity
{
    protected BaseMapping(string nameTabel)
    {
        this.Table(nameTabel);
        this.Id(x => x.Id, map =>
        {
            map.Generator(Generators.Increment);
            map.Column("\"Id\"");

        });
        this.Property(x => x.DateInsert, x =>
        {
            x.Column("\"DateInsert\"");
            x.Insert(false);
            x.Update(false);

        });
    }
}

/// <summary>
/// Справочник пород
/// </summary>
public class Breed : BaseEntity
{
    /// <summary>
    /// Название
    /// </summary>
    public virtual string Name { get; set; }

    /// <summary>
    /// Тип животных 
    /// </summary>
    public virtual PetType PetType { get; set; }
}

public class BreedMap : BaseMapping<Breed>
{
    public BreedMap() : base("\"Breed\"")
    {
        this.Property(x => x.Name, x => x.Column("\"Name\""));
        this.Property(x => x.PetType, x => x.Column("\"PetType\""));
    }
}

Upvotes: 0

Views: 1604

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

I need the field id not to be sent in the insert request and there was no first request...

In case that our DB is supporting IDENTITY (auto increment on DB side), we should not use Increment, but Native setting (or Identity)

//map.Generator(Generators.Increment);
map.Generator(Generators.Native);

Check the doc for detailed explanation

5.1.5.1. generator

small extract

increment

generates identifiers of any integral type that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

...

native/identity

supports identity columns in DB2, MySQL, MS SQL Server and Sybase. The identifier returned by the database is converted to the property type using Convert.ChangeType. Any integral property type is thus supported.

...

Upvotes: 2

Related Questions