如何使用Fluent NHibernate映射没有单个id的实体?

时间:2017-10-25 09:29:00

标签: c# nhibernate fluent-nhibernate

我有一个实体(表格),我希望使用fluent在NHibernate中映射它。堆栈溢出已经存在answer,但对我不起作用(由于声誉低,我无法对该问题添加任何评论)。有人请为我填写以下代码中的问号。

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()方法可以警告我在构造函数中调用了一个虚方法。我应该如何摆脱警告?

3 个答案:

答案 0 :(得分:0)

请改为尝试:

CompositeId()

而不是:

CompositId()

答案 1 :(得分:0)

您应该使用UseCompositeId()方法:

public class MyEntityMap: ClassMap<MyEntity>
{
    public MyEntityMap()
    {
        UseCompositeId()
          .WithKeyProperty(x => x.Id1)
          .WithReferenceProperty(x => x.Id2);
    }
}

参考here

答案 2 :(得分:0)

我在另一个post找到了答案。我不需要从我必须覆盖MyEntityEquals的任何其他类继承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);
         ...
    }
}