I have an entity (a table) that I want to map it in NHibernate using fluent
. There is an answer already for this on stack overflow but does not work for me (I couldn't add any comment to that question due to low reputation). Would someone please complete question marks in following code for me.
class MyEntity: ??? // Entity class has already an Id property
{
public int Id1 {get; set;}
public int Id2 {get; set;}
}
class MyEntityMap: ClassMap<MyEntity>
{
public MyEntityMap() // should mapping be in constructor?
{
...
CompositeId().??? // Gives me warning, call to virtual!
...
}
}
Using CompositeId() method gives me warning that I have called a virtual method within the constructor. How should I get rid of the warning?
I found the answer in another post. I didn't need to inherite MyEntity
from any other class I just had to override Equals
and GetHashCode
. My final code looks like this.
class MyEntity
{
public int Id1 {get; set;}
public int Id2 {get; set;}
public override bool Equals(object obj)
{
var other = obj as MyEntity;
Debug.Assert(other != null, "other != null");
return other.Id1 == this.Id1 && other.Id2 == this.Id2;
}
public override int GetHashCode()
{
unchecked
{
var hash = GetType().GetHashCode();
hash = (hash * 31) ^ Id1.GetHashCode();
hash = (hash * 31) ^ Id2.GetHashCode();
return hash;
}
}
}
class MyEntityMap: ClassMap<MyEntity>
{
public MyEntityMap()
{
...
CompositeId() // I still get the warning, though!
.KeyProperty(x => x.Id1)
.KeyProperty(x => x.Id2);
...
}
}