ForestC
ForestC

Reputation: 213

How to map Id to private backing field in NHibernate's mapping by code?

When using NHibernate's mapping by code functionality, how can I map the Id of an entity to a private backing field?

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

Mapping:

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

Have tried with pointing out the property or field with string but to no avail.

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

...gives me:

An exception of type 'System.Exception' occurred in NHibernate.dll but was not handled in user code Additional information: Invalid expression type: Expected ExpressionType.MemberAccess, Found Constant

Upvotes: 0

Views: 518

Answers (1)

Firo
Firo

Reputation: 30813

Id(x => x.Id, m => m.Access(Accessor.Field)); should work because _id matches LowerCaseUnderscoreStrategy. Note x.Id must be specified like in your first code

Upvotes: 1

Related Questions