![](/img/trans.png)
[英]How to map IDictionary<string, Entity> in Fluent NHibernate
[英]How to map entity with no single id using Fluent NHibernate?
我有一個實體(一個表),我想使用fluent
在NHibernate中映射它。 堆棧溢出時已經有一個答案 ,但對我不起作用(由於信譽低,我無法在該問題上添加任何評論)。 有人可以幫我在下面的代碼中填寫問號。
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!
...
}
}
使用CompositeId()方法會警告我已在構造函數中調用了虛方法。 我應該如何消除警告?
嘗試以下方法:
CompositeId()
代替這個:
CompositId()
您應該使用UseCompositeId()
方法:
public class MyEntityMap: ClassMap<MyEntity>
{
public MyEntityMap()
{
UseCompositeId()
.WithKeyProperty(x => x.Id1)
.WithReferenceProperty(x => x.Id2);
}
}
參考這里 。
我在另一篇文章中找到了答案。 我不需要從其他任何類繼承MyEntity
,而只需要重寫Equals
和GetHashCode
。 我的最終代碼如下所示。
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);
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.