FluentNHibernate - Mapping a class to multiple tables

女生的网名这么多〃 提交于 2019-11-29 17:38:16
Radim Köhler

I do not have simple answer, like CallThis(). I would like to give you suggestion, based on how we are using similar stuff. The solution is base on the standard mapping, hidding its complexity in C# Entities. It is just a draft of the solution so I'll skip the middle Culture table, and will expect that in Lookup_t9n we do store just a culture name (en, cs...)

Let's have this class

public class Lookup {
    public virtual int Id {get; set;}
    public virtual string Code {get; set;}
                                     // for simplicity skipping null checks    
    public virtual DisplayText { get { return Localizations.First().LocalizedText; } } 
    public virtual IList<Localization> Localizations {get; set;}
}

public class Localization { // mapped to Lookup_t9n
    public virtual string CultureName {get; set;}
    public virtual string LocalizedText {get; set;}
}

Having this, we can map the collection of Localizations as HasMany. It could even be mapped as a component (see example of component mapping)

Now, what we do need is to introduce a filter. Example with Fluent. The essential documentation: 18.1. NHibernate filters.

Simplified mapping

filter:

public class CulturFilter : FilterDefinition
{
  public CulturFilter()
  {
    WithName("CulturFilter")
        .AddParameter("culture",NHibernate.NHibernateUtil.String);
  }

collection:

HasMany(x => x.Localization)
    .KeyColumn("Id")
    ...
    .ApplyFilter<CulturFilter>("CultureName = :culture"))
    .Cascade.AllDeleteOrphan();

Finally, we have to introduce some AOP filter, IInterceptor... which will be triggered each time (needed) and adjust the ISession

session
   .EnableFilter("CulturFilter")
   .SetParameter("culture"
     ,System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName);

And now we have Localized string based on current culture, while using standard mapping of localized values as a collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!