如何在NHibernate的代码映射中将Id映射到私有后备字段?

时间:2014-12-07 21:50:45

标签: c# nhibernate orm nhibernate-mapping

当通过代码功能使用NHibernate的映射时,如何将实体的Id映射到私有支持字段?

public abstract class Entity : IEntity
{
    private Guid? _id;

    protected Entity() { }

    protected Entity(Guid? id)
    {
        _id = id;
    }

    #region IEntity Members

    /// <summary>
    /// Gets the unique id for this entity.
    /// </summary>
    /// <value>The id.</value>
    public Guid? Id
    {
        get { return _id;
    }
}

映射:

public abstract class GuidKeyedClassMapping<T> : ClassMapping<T> where T : class, IEntity
{
    protected GuidKeyedClassMapping()
    {
        // What to write here???
        Id(x=> x.Id);
    }
}

尝试用字符串指出属性或字段但无济于事。

Id(x => "_id", m => m.Access(Accessor.Field));

...给我:

  

类型&#39; System.Exception&#39;的例外情况发生在NHibernate.dll但是   未在用户代码中处理附加信息:无效   表达式类型:预期ExpressionType.MemberAccess,Found Constant

1 个答案:

答案 0 :(得分:1)

Id(x => x.Id, m => m.Access(Accessor.Field));应该有效,因为_id匹配LowerCaseUnderscoreStrategy。注意x.Id必须像第一个代码一样指定