【问题标题】:Mapping static/enum/lookup tables such as FooType and BarStatus映射静态/枚举/查找表,例如 FooType 和 BarStatus
【发布时间】:2014-04-22 17:26:07
【问题描述】:

给定以下架构:

Foo
----------
BarId
FooA
FooB
FooTypeId

FooType [LookUp Table]
----------
TypeC
TypeD

Bar
----------
BarZ
BarStatusId

BarStatus [LookUp Table]
----------
TypeE

类型和设置表是静态的,它们包含可以映射到enums 的静态数据。 A.k.a 查找表。 FooBar 是普通表。

我的问题是;如何使用 Fluent NHibernate 惯用地映射这些查找表?最佳做法是什么?

class FooType
{
    TypeC ...
    TypeD ...
}

enum TypeC { ... }
enum TypeD { ... }

在应用程序的生命周期内,是否会在内存/缓存中维护一个 FooType 实体?是否每次想使用时都会从数据库中读取FooType 实体?

从代码创建new FooType() 会导致新的FooType 插入到查找表中,这是不需要的(相同的数据,不同的表ID)

处理查找表时的最佳做法是什么?

FooType 可以创建为单例吗?

【问题讨论】:

    标签: c# nhibernate orm fluent-nhibernate nhibernate-mapping


    【解决方案1】:

    只是我的意见/实践。

    根本不创建查找表 - 保存您的查询不必要的连接。只需将一列直接映射到 enum 属性即可。 NHibernate 通常会使用枚举的字符串版本 - 如果过滤这些列,请为它们添加索引。

    如果你真的想使用整数值(你为什么要使用,db 变得人类无法阅读),但是说你不得不因为一些遗留的 chod,你可以使用属性和约定...

    /// <summary>
    /// flags that a property of type enum is persisted with enum item's numerical value 
    /// </summary>
    [Serializable]
    [AttributeUsage(AttributeTargets.Property)]
    public class NumericEnumAttribute : Attribute
    {
    }
    
    /// <summary>
    /// convention for the <see cref="NumericEnumAttribute"/> - ensures that the enum value is persisted as an integer
    /// </summary>
    public class NumericalEnumConvention : AttributePropertyConvention<NumericEnumAttribute>
    {
        protected override void Apply(NumericEnumAttribute attribute, IPropertyInstance instance)
        {
            instance.CustomType(instance.Property.PropertyType);
        }
    }
    

    如果您想使用只读表 - 那么您应该探索缓存选项和实体配置的只读标志。将实体标记为只读。很好的提示:

    Set up caching on entities and relationships in Fluent Nhibernate?

    【讨论】:

    • 感谢您的回答,不幸的是,我有一个继承的数据库,无法更改架构。我将研究只读标志,感谢您的链接。
    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 2010-10-28
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多