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

How to map entity with no single id using Fluent NHibernate?

我有一个实体(table),我想使用 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() 方法警告我已在构造函数中调用了虚拟方法。我应该如何摆脱警告?

试试这个:

CompositeId()

而不是这个:

CompositId()

你应该使用UseCompositeId()方法:

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

引用here.

我在另一个 post 中找到了答案。我不需要从任何其他 class 继承 MyEntity 我只需要覆盖 EqualsGetHashCode。我的最终代码如下所示。

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);
         ...
    }
}