c# – 与NHibernate的开发人员安全的双向关系

我知道如何映射与NHibernate的双向关系,但有没有人知道一种有效的技术,使他们’开发人员安全’.

我的意思是,只要关系的一端建立,另一端也应该设置,例如:

[Test]
public void TestBidirectionalRelationships_WhenAddingOptionToProduct()
{
    var product = new Product();

    var productOption = new ProductOption();

    product.AddOption(productOption);

    Assert.That(product.Options.Contains(productOption));
    Assert.That(productOption.Product, Is.EqualTo(product);
}

[Test]
public void TestBidirectionalRelationships_WhenSettingProductOnOption()
{
    /* Alternatively, productOption.Product would have no public setter */

    var product = new Product();

    var productOption = new ProductOption();

    productOption.Product = product;

    Assert.That(product.Options.Contains(productOption));
    Assert.That(productOption.Product, Is.EqualTo(product);
}

如何在不使代码变得非常复杂的情况下实现这一目标,同时保持NHibernate的快乐?

一边:

class Product
{
    public Product()
    {
        _Options = new List<ProductOption>();
    }

    ICollection<ProductOption> _Options;
    public virtual IEnumerable<ProductOption> ProductOptions
    {
        get { return _Options.Select(x => x); }
    }

    public virtual AddOption(ProductOption option)
    {
        option.Product = this;
    }

    protected internal virtual AddOptionInternal(ProductOption option)
    {
        _Options.Add(option);
    }
}

很多方面:

class ProductOption
{
    Product _Product;
    public virtual Product Product
    {
        get { return _Product; }
        set
        {
            _Product = value;
            _Product.AddOptionInternal(this);
        }
    }
}

制图:

<class name="Product">
    ...
    <bag name="Options" access="field.pascalcase-underscore">
    ...
<class name="ProductOption">
    ...
    <many-to-one name="Product" access="field.pascalcase-underscore"/>

从集合中删除选项(从任何一方)留下作为练习:-)

相关文章
相关标签/搜索