0

I am using NHibernate Mapping by code with MYSQL, and have mapping as below :-

Id(x => x.Id, map => { map.Column("ID"); map.Generator(Generators.Native); });

and database as below :-

ID int not null AUTO_INCREMENT

i used Generators.Native because database will generates its id by AUTO_INCREMENT . But i would like to manually set id (Id=10) in some cases. How can i change the mapping, if Id=0 then use 'AUTO_INCREMENT' else use the already set Id which is 10.

I checked on internet and got this link (Custom Id Generator) but its for Java + Hibernate. I don't know how to convert this inNHibernate mapping by code for C#.

Community
  • 1
  • 1
Anchit Pancholi
  • 1,174
  • 4
  • 14
  • 40
  • Why would you like to manually set the value of `id` "in some cases"? What are these cases? You're defeating the purpose of an Identity column and quite likely introducing problems that, if not immediate, may make themselves known months or years down the road. Your program should not be affected if there are "gaps" in ID's that are created by deleting records, which is what I'm guessing you're trying to address. – Bob Kaufman Sep 24 '15 at 19:35
  • if data are getting created by frontend then we will use autoincrement, and at run time our system is getting data from some services those have some id which need to be match with our database. For sure our database wont be having this id, so it will be safe for us to set the id and its required. – Anchit Pancholi Sep 24 '15 at 19:40
  • You're treading on thin ice. Suppose this generated ID already exists? Create a separate column that stores this value. – Bob Kaufman Sep 24 '15 at 19:43
  • before insertion i am checking in this id exist or not, If exist then update else insert. – Anchit Pancholi Sep 24 '15 at 19:51

2 Answers2

0

In Hiberante you can define with anotation that use. For example you can define this

@GeneratedValue(strategy=GenerationType.IDENTITY)

Idetentity property take the auto increment from the data base.

hide
  • 92
  • 3
0

What you need is to change your Id defintion from Native to Assigned.

Id(x => x.Id, map => { map.Column("ID"); map.Generator(Generators.Assigned); });