How do I use NHibernateMaps for foreign keys?
I have the following class:
public class Element
{
public Guid Id { get; set; }
public ElementRouting route { get; set; }
}
An Element can be routed to another element in a parent-child - like relationship represented by the following class:
public class ElementRouting
{
public Guid Id { get; set; }
public开发者_运维知识库 Element ParentElement { get; set;}
public Element ChildElement { get; set; }
}
My NHibernateMap for Element looks like this:
public class ElementMapping : ClassMap<Element>
{
public ElementMapping()
{
Id(x => x.Id).GeneratedBy.Assigned();
Not.SelectBeforeUpdate();
References(x => x.Route).Column("ElementRoutingId").Nullable();
Table("Elements");
}
}
...and the map for ElementRouting is as follows:
public class ElementRoutingMapping : ClassMap<ElementRouting>
{
public ElementRoutingMapping()
{
Id(x => x.Id).GeneratedBy.Assigned();
Map(x => x.ChildElement).Column("ElementId").Nullable();
Map(x => x.ParentElement).Column("ElementId").Nullable();
Table("ElementRoutings");
}
}
At the point that I session.Flush()
I have an Element object with null for its property ElementRouting. I get a HibernateException (An exception occurred when executing batch queries) with this InnerException detail:
{"The UPDATE statement conflicted with the FOREIGN KEY constraint "FK54CBB3751C1EAB64". The conflict occurred in database "myDataBaseName", table "dbo.ElementRoutings", column 'Id'.}
Can anyone explain to me what I am doing wrong?
For the Element Mapping's reference to the route, used:
References(x => x.TonsRoute).Column("TonsRouteId").Nullable().Cascade.All();
which does not cause a conflict.
精彩评论