【问题标题】:Fluent NHibernate complicated (?) relationsFluent NHibernate 复杂的(?)关系
【发布时间】:2015-04-29 03:16:43
【问题描述】:

我在使用 Fluent NHibernate 创建关系时遇到了麻烦。 一般来说,我有两个表,资源和项目:

请注意资源表中的 PK 是 id 和 locale。 这意味着,一个项目实际上可以有很少的资源(相同的 id 但不同的语言环境)。

因为它不是一对一的简单关系,所以我在使用 Fluent NHibernate 映射这两者时遇到了麻烦。

克服这个问题的正确方法是什么?

非常感谢!

【问题讨论】:

  • 它是多对多关系,即给定资源(由其{id, locale} 复合键标识)是否可以被不同的项目引用?
  • 一般不会。但听起来使用多对多设计可以让它更简单,不是吗?

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


【解决方案1】:

如果关系是给定的Resource 由单个给定的Item 拥有,则可以这样建模(注意:仅包括重要的部分):

public class Item
{
    public virtual int Id { get; protected set; }
    public virtual IList<Resource> Resources { get; protected set; }
    // Constructor, Equals, GetHashCode, other things ... omitted.
}

public class Resource
{
    public virtual Item Owner { get; protected set; }
    public virtual int ResourceId { get; protected set; }
    public virtual string Locale { get; protected set; }
    public virtual string Value { get; protected set; }
    // Constructor, Equals, GetHashCode, other things ... omitted.
}

并创建以下类映射:

public class ItemMap : ClassMap<Item>
{
    public ItemMap()
    {
        WithTable("items");
        Id(x => x.Id); // add Id generation cfg if needed
        HasMany(x => x.Resources)
            .Inverse()
            .Cascade.All()
    }
}

public class ResourceMap : ClassMap<Resource>
{
    public ResourceMap()
    {
        WithTable("resources")
        CompositeId()
            .KeyProperty(x => x.ResourceId)
            .KeyProperty(x => x.Locale);
        References(x => x.Owner)
    }
}

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 1970-01-01
    • 2011-03-16
    • 2010-11-25
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多