NHibernate.Mapping.ByCode多对多关系

时间:2012-01-24 12:49:49

标签: nhibernate

我创建了两个对象:

public class Set
{
    public Set()
    {
        _sorts = new List<Sort>();
    }
    public virtual int Id { get; set; }
    public virtual string Code { get; set; }
    private ICollection<Sort> _sorts;
    public virtual ICollection<Sort> Sorts
    {
        get { return _sorts; }
        set { _sorts = value; }
    }
}

public class Sort
{
    public Sort()
    {
        _sets = new List<Set>();
    }
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    private ICollection<Set> _sets;
    public virtual ICollection<Set> Sets
    {
        get { return _sets; }
        set { _sets = value; }
    }
}

和2个映射:

public class SetMapping: ClassMapping<Set>
    {
        public SetMapping()
        {
            Table("Sets");
            Id(x => x.Id, map => map.Generator(IdGeneratorSelector.CreateGenerator()));
            Property(x => x.Code, map =>
            {
                map.Length(50);
                map.NotNullable(false);
            });
            Bag(x => x.Sorts, map =>
            {
                map.Key(k =>
                {
                    k.Column("SetId");
                    k.NotNullable(true);
                });
                map.Cascade(Cascade.All);
                map.Table("SetsToSorts");
                map.Inverse(true);

            }, r => r.ManyToMany(m => m.Column("SortId")));
        }
    }

    public class SortMapping: ClassMapping<Sort>
    {
        public SortMapping()
        {
            Table("Sorts");
            Id(x => x.Id, map => map.Generator(IdGeneratorSelector.CreateGenerator()));
            Property(x => x.Name, map =>
            {
                map.Length(50);
                map.NotNullable(false);
            });
        }
    }

用法: 套装可以有很多种 排序可以属于多组。

我想用它作为:

var set = new Set() {Code = "001"};
            var sort = new Sort {Name = "My name"};

            set.Sorts.Add(sort);
            sort.Sets.Add(set);

以某种方式关系还没有工作,因为当我尝试使用上面的代码添加排序来设置例子和提交时,我没有看到任何记录保存到SetsToSorts链接表。

有没有人知道我的地图中缺少什么?或者做错了?

谢谢你, Joost的

1 个答案:

答案 0 :(得分:1)

您的映射表明Set的Sort集合是反向的(map.Inverse(true))。这意味着双向关联的另一方负责持久的更改。 但您的Sort类映射没有任何集合映射。在SetMapping上删除map.Inverse(true)或将非反向集合映射添加到SortMapping。

相关问题