开发者

Fluent NHibernate mapping properties coming from an interface in one place

If many classes implement the same interface(s), is it possible to map those interface properties in one place? There's more code @ pastebin

You can see here that classes have some common interfaces (but not all to make common base class) and I had to repeat mappings.

public class PostMapping : SubclassMap<Post>
{
    public PostMapping()
    {
        Map(x => x.Text, "Text");
        // coming from IMultiCategorizedPage
        HasManyToMany(x => x.Categories).Table("PageCategories").ParentKeyColumn("PageId").ChildKeyColumn("CategoryId").Cascade.SaveUpdate();
        // coming from IMultiTaggedPage
        HasManyToMany(x => x.Tags).Table("PageTags").ParentKeyColumn("PageId").ChildKeyColumn("TagId").Cascade.SaveUpdate();
        // coming from ISearchablePage
        Map(x => ((ISearchablePage)x).SearchIndex, "SearchIndex").LazyLoad();
    }
}
public class ArticleMapping : Su开发者_运维技巧bclassMap<Article>
{
    public ArticleMapping()
    {
        Map(x => x.Text, "Text");
        // coming from ISingleCategorizedPage
        References(x => x.Category, "CategoryId");
        // coming from IMultiTaggedPage
        HasManyToMany(x => x.Tags).Table("PageTags").ParentKeyColumn("PageId").ChildKeyColumn("TagId").Cascade.SaveUpdate();
        // coming from ISearchablePage
        Map(x => ((ISearchablePage)x).SearchIndex, "SearchIndex").LazyLoad();
    }
}


If C# had complete multiple inheritance instead of just multiple interface inheritance then this would be easy. It seems the closest would be creating a single wrapping interface for a mapping base class to hold your common elements. Then, you could create table specific mapping classes that inherit from it. Something along the lines of this code:

public class BasePageMapping : SubclassMap<IPage> //IPage could inherit: IMultiTaggedPage, ISearchablePage
{
    public BasePageMapping()
    {
        Map(x => x.Text, "Text");
        // coming from IMultiTaggedPage
        HasManyToMany(x => x.Tags).Table("PageTags").ParentKeyColumn("PageId").ChildKeyColumn("TagId").Cascade.SaveUpdate();
        // coming from ISearchablePage
        Map(x => ((ISearchablePage)x).SearchIndex, "SearchIndex").LazyLoad();
    }
}

public class PostMapping : BasePageMapping
{
    public PostMapping()  // don't need to specify : base() because it happens automatically
    {
        Table("the specific table");

        HasManyToMany(x => x.Categories).Table("PageCategories").ParentKeyColumn("PageId").ChildKeyColumn("CategoryId").Cascade.SaveUpdate();

        //Other table specific mappings:
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜