Iva*_*vov 3 c# nhibernate orm fluent-nhibernate
我在我的项目中使用NHibernate 3.1和Fluent NHibernate作为ORM.我需要Fluent NHibernate忽略POCO的属性.起初,我的帖子可能看起来与这个问题完全相同,但事实并非如此.
我的并发症首先来自这样一个事实:POCO的定义与映射不同,我使用流利的映射来进行POCO.我还有其他要求,不要在会话工厂配置发生时编写ingore-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();
Run Code Online (Sandbox Code Playgroud)
我使用继承自的标准类映射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();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这篇文章有点老了,但我还是发帖,因为我没有找到关于这个主题的任何最新帖子.我想最简单的方法应该是为每个我们不希望持久保存到表的属性添加属性.通过添加一个扩展,检查它是否有例如.有一个[NoEntity] attibute.
/// <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);
}
}
Run Code Online (Sandbox Code Playgroud)
并在流畅的配置设置:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9050 次 |
| 最近记录: |