我正在尝试使用Id
映射我的实体类中的FluentNHibernate
属性。
我的实体:
public abstract class BaseEntity
{
public int Id { get; set; }
}
public class Entity : BaseEntity
{
public string Name { get; set; }
}
好的,我的映射类如上所述:
public class BaseMapping<E> : ClassMap<E>
{
public BaseMapping(string schema, string table)
{
Schema(schema);
Table(table);
Id(model => typeof(E).GetProperty("Id", typeof(int)), "Id")
.GeneratedBy.Identity()
.Not.Nullable();
}
}
public class EntityMapping : BaseMapping<Entity>
{
public EntityMapping() : base("dbo", "Entities")
{
Map(model => model.Name, "Name")
.Length(50)
.Insert().Update()
.Not.Nullable();
}
}
我收到了这个例外:
{“身份类型必须是整数(int,long,uint,ulong)”}
当我在EntityMapping
类上映射Id属性...
Id(model => model.Id, "Id")
.GeneratedBy.Identity()
.Not.Nullable();
它的作用就像一个魅力。但第一次尝试不起作用。
答案 0 :(得分:0)
首先,您的媒体资源应标记为virtual
。这就是NHibernate框架可以执行其神奇的延迟加载巫术。
话虽如此。让我们假设您的所有实体都来自BaseEntity
。由于这种假设,您可以让typeparam E
了解它始终是BaseEntity
。
完成此操作后,您可以重写BaseMapping<E>
方法。
public class BaseMapping<E> : ClassMap<E>
where E: BaseEntity
{
public BaseMapping(string schema, string table)
{
Schema(schema);
Table(table);
Id(model => model.Id, "Id");
}
}
通过指定where E: BaseEntity
会将E
的属性公开给您的方法。我只测试了这个代码,直到完成多个实体类型的映射方法。
至于你收到消息的原因
typeof(E).GetProperty("Id", typeof(int))
返回PropertyInfo
类型,您需要传递memberExpression
参数的成员表达式。通过挖掘FluentNHibernate的源代码,他们使用Expression通过反射来评估Member
。