我在我的项目中使用 NHibernate 3.1 和 Fluent NHibernate 作为 ORM。我需要有一个被 Fluent NHibernate 忽略的 POCO 属性。起初,我的帖子可能看起来与这个问题,但事实并非如此。
我的复杂性首先来自以下事实:POCO 是在与映射不同的程序集中定义的,并且我正在使用流畅的映射对于我的 POCO。我有额外的要求,不要在会话工厂配置发生的地方编写 inore-property 代码(这发生在模块外部的集中位置),而是作为定义映射的模块的一部分。理想情况下,我相信正确的地方是混凝土ClassMap
实现,因为它确切地知道如何向 ORM 描述 POCO。
然而,我之所以坚持这一点,主要是因为这是我第一次接触 NHibernate 及其流畅的 API。到目前为止,我对它的功能和可扩展性印象非常好,我希望有一种方法可以实现我的需求,将映射相关的代码封装在相应的模块中。
这是我的配置,来自一个集中的地方:
List<Assembly> assemblies = GetModules().Select(x => x.GetType().Assembly).ToList();
ISessionFactory nhibernateSessionFactory = Fluently
.Configure()
.Mappings(m => assemblies.ForEach(asm => m.FluentMappings.AddFromAssembly(asm)))
.Database(
MsSqlConfiguration.MsSql2005
.ShowSql()
.ConnectionString(DatabaseConfig.Instance.ConnectionString))
.ExposeConfiguration(c => new SchemaUpdate(c).Execute(true, true))
.BuildSessionFactory();
我使用继承自的标准类映射ClassMap
:
public class User
{
public virtual int ID { get; set; }
public virtual String Username { get; set; }
public virtual String Password { get; set; }
public virtual DateTime DateCreated { get; set; }
public virtual DateTime DateModified { get; set; }
// Must ignore
public string ComputedProperty { get { ... } }
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("User");
Id(x => x.ID).GeneratedBy.Identity();
Map(m => m.Username).Not.Nullable().Length(255).UniqueKey("User_Username_Unique_Key");
Map(m => m.Password).Not.Nullable().Length(255);
Map(m => m.DateCreated).Not.Nullable();
Map(m => m.DateModified).Not.Nullable();
}
}
我知道这篇文章有点旧,但我还是发布了,因为我没有找到有关该主题的任何最新帖子。
我想最简单的方法应该是为我们不想保留到表中的每个属性添加一个属性。通过添加一个扩展来检查它是否具有例如。具有 [NoEntity] 属性。
/// <summary>
/// Tells a single Property to not be persisted to table.
/// </summary>
public class NoEntity : Attribute { }
/// <summary>
/// Extension to ignore attributes
/// </summary>
public static class FluentIgnore
{
/// <summary>
/// Ignore a single property.
/// Property marked with this attributes will no be persisted to table.
/// </summary>
/// <param name="p">IPropertyIgnorer</param>
/// <param name="propertyType">The type to ignore.</param>
/// <returns>The property to ignore.</returns>
public static IPropertyIgnorer SkipProperty(this IPropertyIgnorer p, Type propertyType)
{
return p.IgnoreProperties(x => x.MemberInfo.GetCustomAttributes(propertyType, false).Length > 0);
}
}
在流畅的配置设置中:
return Fluently.Configure()
.Database(DatabaseConfig)
.Mappings(m => m.AutoMappings.Add(AutoMap.Assembly(typeof(IDependency).Assembly)
.OverrideAll(p => {
p.SkipProperty(typeof(NoEntity));
}).Where(IsEntity)))
.ExposeConfiguration(ValidateSchema)
.ExposeConfiguration(BuildSchema)
.BuildConfiguration();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)