如何通过代码将 Id 映射到 NHibernate 映射中的私有支持字段?
Posted
技术标签:
【中文标题】如何通过代码将 Id 映射到 NHibernate 映射中的私有支持字段?【英文标题】:How to map Id to private backing field in NHibernate's mapping by code? 【发布时间】:2014-12-07 21:50:45 【问题描述】:当使用 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));
...给我:
在 NHibernate.dll 中发生了“System.Exception”类型的异常,但是 未在用户代码中处理附加信息:无效 表达式类型:预期 ExpressionType.MemberAccess,找到常量
【问题讨论】:
【参考方案1】:Id(x => x.Id, m => m.Access(Accessor.Field));
应该可以工作,因为 _id
匹配 LowerCaseUnderscoreStrategy
。注意 x.Id 必须像在您的第一个代码中一样指定
【讨论】:
以上是关于如何通过代码将 Id 映射到 NHibernate 映射中的私有支持字段?的主要内容,如果未能解决你的问题,请参考以下文章
NHibernate 是不是支持使用复合 ID 将抽象类映射到不同的表?