开发者

Fluent Mapping : using join-table and cascades

having a little trouble with a mapping for the following table setup currently:

               Shop
             [1]  [1]                 
            /       \
          [n]       [n]
   Category-[m]---[n]-Article

The behaviour should be the following :

1 - when deleting a shop, all Articles and Categories Should be deleted

2 - when deleting a Category, related Articles should be unassigned but not deleted

3 - when deleting an Article, related Categories should be unassigned but not deleted

Here's the current mapping:

public class ShopMap: ClassMap<Shop>
{
    public ShopMap()
    {
        this.Table("shop");
        Id(x => x.Id).Column("id").GeneratedBy.Native();
        Map(x => x.Name).Column("name");

        HasMany(x => x.Categories).Cascade.AllDeleteOrphan;
        HasMany(x => x.Articles).Cascade.AllDeleteOrphan;
    }
}

public class CategoryMap: ClassMap<Category>
{
    public CategoryMap()
    {
        this.Table("category");
        Id(x => x.Id).Column("id").GeneratedBy.Native();
        Map(x => x.Name).Column("name");

        References(x => x.Shop);

        HasManyToMany(x => x.Articles).Cascade.AllDeleteOrphan()
                                    .Table("article_category")
                                    .ChildKeyColumn("article_id")
                                    .ParentKeyColumn("category_id")
                                        .Inverse();
    }
}

public class ArticleMap: ClassMap<Article>
{
    public ArticleMap()
    {
        this.Table("article");
        Id(x => x.Id).Column("id").GeneratedBy.Native();
        Map(x => x.Name).Column("name");

        References(x => x.Shop);

        HasManyToMany(x => x.Categories).Cascade.All()
                                    .Table("article_category")
        开发者_开发知识库                            .ParentKeyColumn("article_id")
                                    .ChildKeyColumn("category_id");
    }
}

When deleting a Category (Session.Delete()), NH tries to delete the related Articles as well. Changing the Cascade-Mode to SaveUpdate will fix this, but will leave the entries in the link table *article_category*. Summing up : Cascade.SaveUpdate is too lazy, Cascade.All is too eager.

I tried everything that came to my mind in the mappings, but couldn't find a correct way to map this (rather simple schema).

Any ideas on how to (fluently) map this are greatly appreciated!

Thanks in advance

Sebi


The entries are left in the link table because Category.Articles is defined as the inverse side of the relationship. You need to remove the Category from Article.Categories before deleting it in order for the link record to be removed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜