流利的nhibernate sqlstring为密钥生成问号

时间:2014-02-16 12:42:35

标签: c# nhibernate fluent-nhibernate

我在sql中有很多对,我正在尝试使用nhibernate映射它。 在我努力实现这一目标后,我现在越来越近了,但是我的sql字符串nhibernate创建了一个问号,如下所示。我错过了什么吗?

我是否需要在每个类中创建一个add方法以将其他实体添加到其中?

谢谢,

我的问题 - 由流利的nhibernate生成的sql字符串

... y=productcat1_.itm_Key WHERE productcat0_.itr_Key=?

对象A

public class Range : IEntity
{
    public virtual IList<Item> Items { get; set; }
}

对象B

public class Item : IEntity
{
    public virtual IList<Range> Ranges { get; set; } 
}

映射

// Item mapping
mapping.HasManyToMany(x => x.Ranges)
            .Table("itr_RangeItemsAssoc")
            .ParentKeyColumn("itm_Key")
            .ChildKeyColumn("itr_ItemsKey")
            .Cascade.SaveUpdate().LazyLoad();

// Range mapping
mapping.HasManyToMany(x => x.Items)
            .Table("itr_RangeItemsAssoc")
            .ParentKeyColumn("itr_Key")
            .ChildKeyColumn("itr_ItemRangeKey")
            .Cascade.SaveUpdate().LazyLoad();

更新

我已经在我的实体上添加了以下方法,虽然我没有在任何地方调用它们。?

public class Range : IEntity
{
    ....

    public virtual void AddItem(Item item)
    {
        item.Ranges.Add(this);
        Items.Add(item);
    }
}

public class Item : IEntity
{
    ...

    public virtual void AddRange(Range range)
    {
        range.Items.Add(this);
        Ranges.Add(range);
    }
}

更新2 - 映射更正

mapping.HasManyToMany(x => x.Ranges)
            .Table("itr_RangeItemsAssoc")  // name of the look up table
            .ParentKeyColumn("itr_ItemsKey")  // key for item in the lookup table
            .ChildKeyColumn("itm_Key")  // key column in the item table
            .Cascade.SaveUpdate().LazyLoad().Inverse();
    }


mapping.HasManyToMany(x => x.Items)
            .Table("itr_RangeItemsAssoc")  // name of the look up table
            .ParentKeyColumn("itr_ItemRangeKey")  // key for the range in the lookup tablei
            .ChildKeyColumn("itr_Key")  // key column in the range table
            .Cascade.SaveUpdate().LazyLoad();

非常感谢,

1 个答案:

答案 0 :(得分:0)

有两件事需要提及。

首先,多对多由配对表表示,有两列。这些都扮演着亲子和亲子的角色。

其次,一端必须标记为反向。项目下方标有.Inverse()

有一个Item映射

的示例
public class ItemMap : ClassMap<Item>
{
    public LibraryMap()
    {
         // table, id, other properties
         ...
         HasManyToMany(x => x.Ranges)
            .Table("itr_RangeItemsAssoc")
            .ParentKeyColumn("itr_ItemRangeKey") // not itm_Key
            .ChildKeyColumn("itr_ItemsKey")
            .Cascade.SaveUpdate()
            .LazyLoad();

Range

的相似内容
HasManyToMany(x => x.Items)
    .Table("itr_RangeItemsAssoc")
    .ParentKeyColumn("itr_ItemsKey") // not itr_Key
    .ChildKeyColumn("itr_ItemRangeKey")
    .Cascade.SaveUpdate()
    .LazyLoad()
    // here, the inverse
    .Inverse() // one end must be marked as inverse
    ;

在这里,您可以了解背后的映射:6.8. Bidirectional Associations

可以在此处找到多对多的流畅映射示例:Mapping-by-Code - OneToMany and other collection-based relation types (文章的后半部分)

相关问题