I want generate INSERT which include my Primary Key (not generated) by NHibernate. How to map Id column for this?

I have table CUSTOMER where CUSTOMER_ID is primary key.

Table

  

Code:

CREATE TABLE [CUSTOMER](
    [CUSTOMER_ID] [int] NOT NULL,
    [START_DATE] [varchar(30)] NOT NULL,
CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED ( [CUSTOMER_ID] ASC …..

Mapping

Code:

public class CustomerMap : ClassMap<Customer> {
    public CustomerMap()
    {
        WithTable(“CUSTOMER”);
        Id(x => x.CustomerID, “CUSTOMER_ID”);
        Map(x => x.Name, “NAME”);
    }
}

I need to handle assigning of the CustomerID property manually. For
example I created new Customer with CustomerID = 777 and Name
= “Andriy Buday”
.

When I call method Session.Save(customer);
I want NHibernate to generate me SQL like this:

  

Code:

INSERT INTO [CUSTOMER] ([CUSTOMER_ID] ,[NAME]) VALUES (777,‘Andriy Buday’)

Unfortunately I’m getting errors.

Main issue here is that Nhibernate tries to generate ID for me. But I want to save my entity exactly with 777.

Solution

So I need to manually setup my ID property with adding GeneratedBy.Assigned();
Like here:

Code:

Id(x => x.CustomerID, “CUSTOMER_ID”)
      .GeneratedBy.Assigned();

If you haven't subsribed yet, you can subsribe below: