NHibernate WARNING and the data is not saved - nhibernate

While I am saving by calling SaveOrUpdate(), I got this warning and the data is not saving in the database after calling Transaction.Commit().
NHibernate.Engine.ForeignKeys - Unable
to determine if [project name] with
assigned identifier [primarykey] is
transient or detached; querying the
database. Use explicit Save() or
Update() in session to prevent this.
I am inserting a new object. Google search tell me to call Save() instead of SaveOrUpdate(): means Save() is only for inserting.
I search in Google and do not see much about this.
Could anyone give me suggestion for this problem or this warning?
Edit:
Here is the simulated sample mapping files -
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly=""
namespace="">
<class name="Customer" table="[dbo].[Customer]" optimistic-lock="none" >
<id name="CustomerId" column="CustomerId" >
<generator class="assigned"/>
</id>
<property name="Name" column="Name" />
<property name="Age" column="Age" />
<set name="CustomerDetails" cascade="none" inverse="true" fetch="select">
<key>
<column name="CustomerId"/>
</key>
<one-to-many class="CustomerDetail"/>
</set>
<many-to-one name="MGender" fetch="select" cascade="none">
<column name="GenderCode"/>
</many-to-one>
</class>
</hibernate-mapping>
<class name="CustomerDetails" table="[dbo].[CustomerDetail]" optimistic-lock="none" >
<id name="CustomerDetailId" column="CustomerDetailId" >
<generator class="assigned"/>
</id>
<property name="Detail1" column="Detail1" />
<many-to-one name="Customer" fetch="select" cascade="none">
<column name="CustomerId"/>
</many-to-one>
</class>
<class name="MGender" table="[dbo].[MGender]" optimistic-lock="none" >
<id name="GenderCode" column="GenderCode" >
<generator class="assigned"/>
</id>
<property name="Description" column="Description" />
<set name="Customers" cascade="none" inverse="true" fetch="select">
<key>
<column name="GenderCode"/>
</key>
<one-to-many class="Customer"/>
</set>
</class>

You're using an assigned identifier so you need to set the unsaved-value attribute so that NHibernate can determine if an entity should be inserted or updated. Or you can explicitly call Save for new entities.
<id name="CustomerId" column="CustomerId" unsaved-value="???" >
<generator class="assigned"/>
</id>

Please note that if you are using a custom id, ie not using Id(x => x.Id).GeneratedBy.Assigned() and you do not have any version or timestamp columns, there is no way NHibernate would know if thuis is a new row or an existing one. So, I fixed my problem by using GeneratedBy.UuidString(). Works like a charm. Almost put my code into production with this error message, fortunately my information was being saved.

Related

Yet another one on "deleted object would be re-saved by cascade (remove deleted object from associations)"

Most all of the references to this NHibernate error (in the title) talk about child objects being deleted while still contained in a parent collection that would only re-save them later negating their "delete" (which is what the error states and the suggestion to remove object from associations that are re-saving it).
But in my case, the error happens while deleting the parent record (then the "child" is deleted via the association, so I don't want the association removed, as the error suggest)
It would have made sense if that happened every time, but I only observe this error intermittently, running exactly the same code but only against particular records. Other identical records don't trigger the condition and the delete goes through (all the time I deal with one Customer with two address-es.)
Not sure how much and what code to show. This is my "parent" object mapping:
I've got a OneCustomer-to-ManyAddresses relation mapped as a "set" of CustomerAddress "composite elements"
<class name="Customer" table="Customer">
<id name="Id" column="[Id]" type="Guid">
<generator class="guid" />
</id>
...
<set name="AddressList" lazy="true" table="CustomerAddress" cascade="all-delete-orphan" >
<key column="[CustomerId]"/>
<composite-element class="CustomerAddress">
<parent name="Customer"/>
<many-to-one name="Address"
class="Address"
column="[AddressId]"
not-null="true"
cascade="all"/>
...
</composite-element>
</set>
And this is the mapping for the "composite" object CustomerAddress:
<class name="CustomerAddress" table="CustomerAddress" >
<id name="Id" column="[Id]" type="Guid">
<generator class="guid" />
</id>
<many-to-one
name="Address"
column="[AddressId]"
class="Address"
not-null="true"
cascade="all"/>
<many-to-one
name="Customer"
column="[CustomerId]"
class="Customer"
not-null="true"
cascade="all"/>
...
</class>
What is the explanation of the error and its intermittent nature?
ADDITIONAL INFO
After further examination - looking for another collection that may hold a reference to same "Address" child, I saw the following mapping:
<class name="Address" table="Address">
<id name="Id" column="[id]" type="Guid" >
<generator class="guid" />
</id>
<!-- REMOVING THE FOLLOWING <BAG> SEEMS TO BE FIXING MY ISSUE -->
<bag name="CustomerAddressList" inverse="true" cascade="none" lazy="false" >
<key>
<column name="[AddressId]" />
</key>
<one-to-many class="CustomerAddress" />
</bag>
</class>
Removing the <bag name="CustomerAddressList"... seems to fix my issue. Explanation?
I'm going to have a guess:
You have a bi-directional association, but you haven't specified that one of them is the non-owner (by setting "inverse = true").
Try modifying the CustomerAddress relationship as follows:
<class name="CustomerAddress" table="CustomerAddress" >
<id name="Id" column="[Id]" type="Guid">
<generator class="guid" />
</id>
<many-to-one
name="Address"
column="[AddressId]"
class="Address"
not-null="true"
cascade="all"/>
<many-to-one
name="Customer"
column="[CustomerId]"
class="Customer"
not-null="true"
cascade="all"
inverse="true"
/>
...
</class>
why do you have two mappings for CustomerAddress table (one as composite Element and one as Entity)? remove the entity mapping for Customer address and it should work.

NHibernate removing FK in one-to-many association on update

First, here is my relation
<class name="ServiceStep">
<id name="Id">
<generator class="guid.comb"/>
</id>
<set name="AdditionalInfoRows" cascade="save-update" >
<key column="ServiceStepId"/>
<one-to-many class="AdditionalInfoRow"/>
</set>
<class name="AdditionalInfoRow">
<id name="Id">
<generator class="guid.comb"/>
</id>
<set name="AdditionalInfos" cascade="save-update" >
<key column="AdditionInfoRowId"/>
<one-to-many class="AdditionalInfo"/>
</set>
Now, when I create new ServiceStep and add AdditionalInfoRows into it, everything works fine and it's correctly persisted.
The problem is by update. I load ServiceStep and the Set is correctly loaded with AdditionalInfoRows. In my application I add new AdditionalInfoRows to this set. Then I call SaveOrUpdate on ServiceStep. Newly addes AdditionalInfoRows are persisted correctly but my original list looses the connection. FK in AdditionalInfoRows which should point to ServiceStep is set to NULL by NHibernate.
Hope somebody can point me into right direction.
You can try including something like this in your AdditionalInfoRow mapping:
<many-to-one name="ServiceStep" class="ServiceStep">
<column name="ServiceStepId" not-null="true"/>
</many-to-one>
to look like,
<class name="AdditionalInfoRow">
<id name="Id">
<generator class="guid.comb"/>
</id>
<set name="AdditionalInfos" cascade="save-update" >
<key column="AdditionInfoRowId"/>
<one-to-many class="AdditionalInfo"/>
</set>
<many-to-one name="ServiceStep" class="ServiceStep">
<column name="ServiceStepId" not-null="true"/>
</many-to-one>
</class>

nhibernate and All-delete-orphan

i have a an entity class which has a bag of child entity class like so(copied relevant lines):
<class name="Entity" table="Entities" lazy="false">
<id name="ID">
<generator class="guid"/>
</id>
<bag name="SubEntities" table="SubEntities" cascade="all-delete-orphan">
<key column="EntityID"/>
<one-to-many class="SubEntity"/>
</bag>
</class>
Now, the mapping works well and as expected in most cases (when i delete/save it cascades), but when i try to remove some subentity(child) from the bag in the Entity(parent) class - the change does not cascade and all i see in the DB is that the subentitiy's foreign key was changed to null, and not deleted as i would like.
I've read something about nhibernate not realizing which line it needs to delete in the database (no unique id for the row) - so i tried to use the idbag instead of the bag - but the idbag does not allow a one-to-many collection in it, i've tried something of the sort:
<idbag name="SubEntities" table="SubEntities" cascade="all-delete-orphan">
<collection-id column="Id" type="Guid">
<generator class="guid"/>
</collection-id>
<key column="EntityID"/>
<one-to-many class="SubEntity"/>
</idbag>
which of course gives the error that one-to-many isnt allowed there.
Even when i try to use the component (which i dont want as i want the child is also an entity) - i cant use an external hbm file to define it (the subentity is a rather large class by itself)
so setting the entity's propertise in the parent's hbm files isnt a good idea as well.
Could anyone help me out with explaning whats wrong and how am i supposed to fix it? i really need the subentity to be removed!
Thanks!
As requested - I"m pasting my hbm files:
For Entity:
<?xml version="1.0" encoding="utf-8" ?>
- <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Com.Project.Shared.Common" namespace="Com.Project.Shared.Common.Entities">
- <class name="Entity" table="Entities" lazy="false">
- <id name="ID">
<generator class="guid" />
</id>
<property name="Name" />
<property name="Description" />
<property name="EndTime" />
<property name="StartTime" />
<property name="State" />
<property name="Stored" />
<property name="ClassRoomID" />
<property name="Score" />
<many-to-one name="Network" class="Network" column="NetworkID" />
- <bag name="Scenarios" cascade="all">
<key column="EntityID" />
<one-to-many class="EntScenario" />
</bag>
- <bag name="TimeLineEvents" order-by="TimeStamp" cascade="all">
<key column="EntityID" />
<one-to-many class="TimeLineEvent" />
</bag>
- <bag name="SubEntity" table="SubEntities" cascade="all-delete-orphan">
<key column="EntityID" />
<one-to-many class="SubEntity" />
</bag>
</class>
</hibernate-mapping>
for SubEntity:
<?xml version="1.0" encoding="utf-8" ?>
- <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Com.Project.Shared.Common" namespace="Com.Project.Shared.Common.Entities">
- <class name="SubEntity" table="SubEntities" lazy="false">
- <id name="ID">
<generator class="guid" />
</id>
<many-to-one name="Name" class="EntName" column="NameID" />
<many-to-one name="Station" class="EntStation" column="StationID" />
- <bag name="Performances" table="EntPerformances" cascade="all">
<key column="SubEntityID" />
- <composite-element class="Performance">
<property name="Rank" />
<property name="Remark" />
<many-to-one name="Category" class="PerformanceCategory" column="CategoryID" index="ListIndex" />
</composite-element>
</bag>
</class>
</hibernate-mapping>
The tester i use is:
Entity newEntity = _dal.GetAll<Entity>()[0];
ObservableCollection<SubEntity> subEntities = newEntity.ObservableSubEntities;
subEntities .RemoveAt(1);
_dal.SaveItem<Entity>(newEntity);
This just turned the EntityID column in subentity into Null - but doesnt delete it.
I appericiate your help, guys.
The bag needs to have inverse="true" on it if you want it to work as expected.
This tells NHibernate that Entity is responsible to managing the relationship (and you'll be able to make your FK column non-null)

NHibernate: Mapping multiple classes to the same view

I need to map two different classes to the same view and receive an error that a duplicate mapping exists. Is this possible in NHibernate? If not, can anyone give direction as to how I can solve this mapping problem.
I work with views which are set in stone. One view brings back data needed to split into two classes. The view looks like:
vw_player_points
----------------
Id
GameID
PlayerID
Points
The classes need to be 'player', with a list of games played
select gameid from vw_player_points where playerid = <PlayerID>
And each 'game' needs a list of players and their points:
select playerid, points from vw_player_points where gameid = <GameID>
I've tried table-per-concrete class inheritance aswell as mapping to the same view twice, but have had no joy :(
Here's the 'rough' mappings put into one xml snippet. Notice I also need to map to an interface (which works)
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainModel" namespace="Test">
<class name="IPlayer" abstract="true">
<id name="Id" column="id">
<generator class="assigned"/>
</id>
<union-subclass name="Player" table="vw_player">
<bag name="Games">
<key column="player_id"/>
<one-to-many class="Test.IGame" not-found="ignore"/>
</bag>
</union-subclass>
</class>
<class name="IGame" abstract="true">
<id name="Id" column="game_id">
<generator class="assigned"/>
</id>
<union-subclass name="Game" table="vw_player_points">
<bag name="Points">
<key column="game_id"/>
<one-to-many class="Test.IPlayerPoints" not-found="ignore"/>
</bag>
</union-subclass>
</class>
<class name="IPlayerPoints" abstract="true">
<id name="Id" column="id">
<generator class="assigned"/>
</id>
<union-subclass name="PlayerPoints" table="vw_player_points">
<property not-null="false" name="PlayerId" column="player_id"/>
<property not-null="false" name="Points" column="points"/>
</union-subclass>
</class>
</hibernate-mapping>
It seems impossible to map multiple classes to a single view when using abstract/sub-class mapping of the form:
<class name="I[Entity]" abstract="true">
<union-subclass name="[Entity]">
...
</union-subclass>
</class>
I ended up mapping directly to the concrete classes using the proprty-ref attribute which works correctly:
<class name="Game" table="vw_player_points">
<id name="Id" column="id">
<generator class="hilo"/>
</id>
<property not-null="false" name="GameId" column="gameid"/>
<bag name="Points">
<key column="gameid" property-ref="GameId"/>
<one-to-many class="PlayerPoints" not-found="ignore"/>
</bag>
</class>
<class name="PlayerPoints" table="vw_player_points">
<id name="Id" column="id">
<generator class="hilo"/>
</id>
<property not-null="false" name="PlayerId" column="playerid"/>
<property not-null="false" name="Points" column="points"/>
</class>
Perhaps an 'abstract' sub-mapping type would negate the use of the union-subclass hack mapping to interfaces.

nhibernate newbe question ... easy one here

I'm new to nhibernate so this should be easy. I have a mapping file as below although I deleted some fields that aren't relevant to this question. The streamfields class contains a bag of fieldmappings. I want the join to be on field_no column but the sql that is sent is on the id field (str_fld_id") as seen below.
I see what the below sql is doing but it's not what I wanted. It's trying to query the field_mappings table based on the values found in the id column str_fld_id in the StreamFields class when I thought it was clear I wanted the field_no to be used on both ends. I say I thought it was clear because the mapping for the field_mapping class has the below attribute and they both have the same named field
Below is in my FieldMappings mapping file.
<many-to-one name="FieldNo" cascade="none" column="`Field_No`" not-null="true">
Sql sent
NHibernate: SELECT fkfieldmap0_.[field_no] as field5_1_, fkfieldmap0_.[Mapping_Id] as Mapping1_1_, fkfieldmap0_.[Mapping_Id] as Mapping1_3_0_, fkfieldmap0_.[Std_fld_Id] as Std2_3_0_, fkfieldmap0_.[Field_Position] as Field3_3_0_, fkfieldmap0_.[Field_No] as Field4_3_0_ FROM [Field_Mappings] fkfieldmap0_ WHERE fkfieldmap0_.[field_no]=#p0; #p0 = '20'
StreamFields mapping
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="DataTransfer.StreamFields,DataTransfer" table="`stream_fields`" lazy="true">
<id name="StrFldId" column="`str_fld_id`" type="int">
<generator class="native" />
</id>
<property type="int" not-null="true" name="FieldNo" column="`field_no`" />
<many-to-one name="StreamId" cascade="none" column="`stream_Id`" />
<bag name="FkFieldMappingsStreamFields" inverse="true" lazy="false" cascade="all">
<key column="`field_no`" />
<one-to-many class="DataTransfer.FieldMappings,DataTransfer"/>
</bag>
</class>
[Edited - with old comments]
Okay, i think i finally got you right and i might admit the problems i had understanding what you want took me a while and result of the lack of information you provided. In the future please provide the mapping of both tables clarify on the point wheather it is a mapping or a query issue. Thx.
IMO you have misunderstood the idea of a parent/child-relation.
The bag you mentioned like to have within the StreamFields class shouldn't be a bag but a direct association. Like this:
<class name="DataTransfer.StreamFields,DataTransfer" table="stream_fields" >
<id name="StrFldId" column="str_fld_id" type="int">
<generator class="native" />
</id>
<property type="int" not-null="true" name="FieldNo" column="field_no" />
<many-to-one name="FieldMapping" class="FiueldMapping" column="Field_No" />
</class>
This of course will only work if you have a property of type FiledMapping in your class.
You want to map FieldMapping to the column Field_No within StreamFields class. There can only be one value within this column, so a bag makes no sense at all. If you want to have a bag of course you can keep it the way it already worked but be aware that the 'key-column' within the bag refers to the child table - in an other way it makes no sense cause a ForeignKey has to map to a PrimaryKey on its parent table. This ensures it is unique and set.
I really don't want to rant but would strongly encourage you to review the hibernate reference about collection mapping to get a deeper clue however.
Hopely this will solve your problem.
Below are the mappings for the classes.
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="DataTransfer.StreamFields,DataTransfer" table="`stream_fields`" lazy="true">
<id name="StrFldId" column="`str_fld_id`" type="int">
<generator class="native" />
</id>
<property type="string" length="50" name="FieldName" column="`field_name`" />
<property type="int" name="InputFieldPosition" column="`input_field_position`" />
<property type="int" name="Start" column="`start`" />
<property type="int" name="Width" column="`width`" />
<property type="string" length="50" name="Datatype" column="`datatype`" />
<property type="int" not-null="true" name="FieldNo" column="`field_no`" />
<property type="int" name="FieldOrder" column="`field_order`" />
<property type="int" name="StdId" column="`Std_Id`" />
<many-to-one name="StreamId" cascade="none" column="`stream_Id`" />
<bag name="FkFieldMappingsStreamFields" inverse="true" lazy="false" cascade="all">
<key column="`field_no`" />
<one-to-many class="DataTransfer.FieldMappings,DataTransfer"/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="DataTransfer.FieldMappings,DataTransfer" table="`Field_Mappings`" lazy="false">
<id name="MappingId" column="`Mapping_Id`" type="int">
<generator class="native" />
</id>
<property type="int" name="StdFldId" column="`Std_fld_Id`" />
<property type="int" name="FieldPosition" column="`Field_Position`" />
<many-to-one name="FieldNo" cascade="none" column="`Field_No`" not-null="true" property-ref="FieldNo" />
</class>
</hibernate-mapping>
To make things easy on myself, there is one record in stream_fields and the field_no value is 1 and 20 is the value in StrFldId.
SELECT fkfieldmap0_.[field_no] as field5_1_, fkfieldmap0_.[Mapping_Id] as Mapping1_1_, fkfieldmap0_.[Mapping_Id] as Mapping1_3_0_, fkfieldmap0_.[Std_fld_Id] as Std2_3_0_, fkfieldmap0_.[Field_Position] as Field3_3_0_, fkfieldmap0_.[Field_No] as Field4_3_0_ FROM [Field_Mappings] fkfieldmap0_ WHERE fkfieldmap0_.[field_no]=#p0; #p0 = '20' –