orm - NHibernate SaveOrUpdate without primary key -
the situation
i've got database table mapped via nhibernate (3.3.3-sp1). application running on .net4.0 , mapping done via fluentnhibernate (1.4.0).
create table movies (id int primary key, yearpublished datetime not null, name nvarchar(500) not null, description ntext not null)
the data this:
id | yearpublished | name | description ---+---------------+------------------------+-------------------------------------------- 1 | 1968 | 2001: space oddyssey | epic drama of adventure , exploration
the problem
i'm creating new entities of table , want avoid adding more 1 entity same real world thing. know there session.saveorupdate
, there way make work composite , natural ids that's not want since entities have primary key , need composite key making sure no duplicates in db.
var movie = new movies { yearpublished = 1968, name = "2001: space oddyssey", description = "an awesome journey jupiter" }; // behavior right now: // adds new movie besides fact // movie in database // has 2 entries session.saveorupdate(movie); assert.istrue(movie.id == 2 && movie.description == "an awesome journey jupiter"); // want able define // makes object unique other primary key; // in scenario should combination // of "yearpublished" , "name" session.myawesomesaveorupdate(movie); assert.istrue(movie.id == 1 && movie.description == "an epic drama of adventure , exploration");
is functionality in place in nhibernate (e.g. through custom mapping) or have fetch candidates db , hand?
thanks!
i solve adding unique constraint on natural key fields in database , using exception converter convert sql server exception 1 application can handle.
public class sqlserverexceptionconverter : isqlexceptionconverter { public exception convert(adoexceptioncontextinfo adoexceptioncontextinfo) { var sqlexception = adoexceptioncontextinfo.sqlexception sqlexception; if (sqlexception != null) { // 2601 unique key, 2627 unique index; same thing: // http://blog.sqlauthority.com/2007/04/26/sql-server-difference-between-unique-index-vs-unique-constraint/ if (sqlexception.number == 2601 || sqlexception.number == 2627) { // custom exception return new uniquekeyexception(sqlexception.message, sqlexception); } } return adoexceptioncontextinfo.sqlexception; } }
another approach can think of query database matching record before insert that's not foolproof because record inserted between select , insert.
Comments
Post a Comment