Reputation: 615
I have a situation where I have a table with 3 columns which contain IDs referencing defferent tables. In addition to those 3 columns I have a few columns with some properties.
Let's say that the 3 columns are Foo, Bar, Baz. Foo is never null, and exactly one of Bar, Baz is null.
My entity and mapping looks like this (please keep in mind that I wanted to keep things simple):
public class FooBarBaz
{
public virtual Foo Foo { get; set; }
public virtual Bar Bar { get; set; }
public virtual Baz Baz { get; set; }
public virtual string Prop { get; set; }
public override bool Equals(Object obj)
{
/* checks for nulls etc. in the end
returns Foo == obj.Foo && Bar == obj.Bar && Baz == obj.Baz */
}
public override int GetHashCode()
{
/* builds unique string for (Foo,Bar,Baz)
taking nulls into account and gets it's hashcode */
}
}
public class FooBarBazMap : ClassMap<FooBarBaz>
{
public FooBarBazMap()
{
CompositeId()
.KeyReference(x => x.Foo, "Foo_Id")
.KeyReference(x => x.Bar, "Bar_Id")
.KeyReference(x => x.Baz, "Baz_Id");
Map(x => x.Prop);
}
}
I created manually a row where all three columns are not null, and this mapping works totally fine. But my application logic is based on the fact that always one of the two (Bar, Baz) is null and in that situation NHibernate returns null as FooBarBaz entity.
How can I overcome this problem? Does NHibernate allow null values in CompositeId?
Upvotes: 4
Views: 1926
Reputation: 30803
nhibernate is an abstraction on top of relational databases and relational databases do not allow null values in primary key columns (in fact all pk columns have not null constraints).
Assuming this table is a linktable between the 3 entities i would map it as a component. If you post the association between Foo bar and baz i can give an example.
Upvotes: 4