实体框架中内容的国际化

Iai*_*way 18 entity-framework internationalization

我不断遇到i18n要求,我的数据(不是我的用户界面)需要国际化.

public class FooEntity
{
  public long Id { get; set; }
  public string Code { get; set; } // Some values might not need i18n
  public string Name { get; set } // but e.g. this needs internationalized
  public string Description { get; set; } // and this too
}
Run Code Online (Sandbox Code Playgroud)

我可以使用哪些方法?

我试过的一些事情: -

1)在db中存储资源键

public class FooEntity
{
  ...
  public string NameKey { get; set; }
  public string DescriptionKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
  • 优点:无需复杂的查询即可获得翻译的实体.System.Globalization处理你的后备.
  • 缺点:管理员用户无法轻松管理翻译(每当我Foo的更改时都必须部署资源文件).

2)使用LocalizableString实体类型

public class FooEntity
{
  ...

  public int NameId { get; set; }
  public virtual LocalizableString Name { get; set; }

  public int NameId { get; set; }
  public virtual LocalizableString Description { get; set; }
}

public class LocalizableString
{
  public int Id { get; set; }

  public ICollection<LocalizedString> LocalizedStrings { get; set; }
}

public class LocalizedString
{
  public int Id { get; set; }

  public int ParentId { get; set; }
  public virtual LocalizableString Parent { get; set; }

  public int LanguageId { get; set; }
  public virtual Language Language { get; set; }

  public string Value { get; set; }
}

public class Language
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string CultureCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
  • 优点:同一个表中的所有本地化字符串.验证可以按字符串执行.
  • 缺点:查询很可怕.必须.为父实体上的每个可本地化字符串包含LocalizedStrings表一次.后退很难,涉及广泛的加入.在检索例如表的数据时,没有找到避免N + 1的方法.

3)使用包含所有不变属性的父实体和包含所有本地化属性的子实体

public class FooEntity
{
  ...
  public ICollection<FooTranslation> Translations { get; set; }
}

public class FooTranslation
{
  public long Id { get; set; }

  public int ParentId { get; set; }
  public virtual FooEntity Parent { get; set; }

  public int LanguageId { get; set; }
  public virtual Language Language { get; set; }

  public string Name { get; set }
  public string Description { get; set; }
}

public class Language
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string CultureCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
  • 优点:没有那么难(但仍然太难!)将实体完整翻译成内存.
  • 缺点:实体数量加倍.无法处理实体的部分翻译 - 特别是在名称来自es但描述来自的情况下es-AR.

我对解决方案有三个要求

  • 用户可以在运行时编辑实体,语言和翻译

  • 根据System.Globalization,用户可以提供部分翻译,其中包含来自回退的缺失字符串

  • 可以将实体带入内存而不会遇到例如N + 1个问题

ren*_*ene 1

为什么不两全其美呢?有一个 CustomResourceManager 来处理资源加载并选择正确的区域性,并使用 CustomResourceReader 来使用您喜欢的任何后备存储。基本实现可能如下所示,依赖于 Resourceky 的约定,即 Typename_PropertyName_PropertyValue。如果由于某种原因需要更改后备存储的结构(csv/excel/mssql/表结构),您只需更改 ResourceReader 的实现即可。

作为额外的奖励,我还得到了真实/透明的代理。

资源管理器

class MyRM:ResourceManager
{
    readonly Dictionary<CultureInfo, ResourceSet>  sets = new Dictionary<CultureInfo, ResourceSet>();


    public void UnCache(CultureInfo ci)
    {
        sets.Remove(ci):
    }

    protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
    {
        ResourceSet set;
        if (!sets.TryGetValue(culture, out set))
        {
            IResourceReader rdr = new MyRR(culture);
            set = new ResourceSet(rdr);
            sets.Add(culture,set);
        }
        return set; 
    }

    // sets Localized values on properties
    public T GetEntity<T>(T obj)
    {
        var entityType = typeof(T);
        foreach (var prop in entityType.GetProperties(
                    BindingFlags.Instance   
                    | BindingFlags.Public)
            .Where(p => p.PropertyType == typeof(string) 
                && p.CanWrite 
                && p.CanRead))
        {
            // FooEntity_Name_(content of Name field)
            var key = String.Format("{0}_{1}_{2}", 
                entityType.Name, 
                prop.Name, 
                prop.GetValue(obj,null));

            var val = GetString(key);
            // only set if a value was found
            if (!String.IsNullOrEmpty(val))
            {
                prop.SetValue(obj, val, null);
            }
        }
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)

资源阅读器

class MyRR:IResourceReader
{
    private readonly Dictionary<string, string> _dict;

    public MyRR(CultureInfo ci)
    {
        _dict = new Dictionary<string, string>();
        // get from some storage (here a hardcoded Dictionary)
        // You have to be able to deliver a IDictionaryEnumerator
        switch (ci.Name)
        {
            case "nl-NL":
                _dict.Add("FooEntity_Name_Dutch", "nederlands");
                _dict.Add("FooEntity_Name_German", "duits");
                break;
            case "en-US":
                _dict.Add("FooEntity_Name_Dutch", "The Netherlands");
                break;
            case "en":
                _dict.Add("FooEntity_Name_Dutch", "undutchables");
                _dict.Add("FooEntity_Name_German", "german");
                break;
            case "": // invariant
                _dict.Add("FooEntity_Name_Dutch", "dutch");
                _dict.Add("FooEntity_Name_German", "german?");
                break;
            default:
                Trace.WriteLine(ci.Name+" has no resources");
                break;
        }

    }

    public System.Collections.IDictionaryEnumerator GetEnumerator()
    {
        return _dict.GetEnumerator();
    }
    // left out not implemented interface members
  }
Run Code Online (Sandbox Code Playgroud)

用法

var rm = new MyRM(); 

var f = new FooEntity();
f.Name = "Dutch";
var fl = rm.GetEntity(f);
Console.WriteLine(f.Name);

Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");

f.Name = "Dutch";
var dl = rm.GetEntity(f);
Console.WriteLine(f.Name);
Run Code Online (Sandbox Code Playgroud)

真实代理

public class Localizer<T>: RealProxy
{
    MyRM rm = new MyRM();
    private T obj; 

    public Localizer(T o)
        : base(typeof(T))
    {
        obj = o;
    }

    public override IMessage Invoke(IMessage msg)
    {
        var meth = msg.Properties["__MethodName"].ToString();
        var bf = BindingFlags.Public | BindingFlags.Instance ;
        if (meth.StartsWith("set_"))
        {
            meth = meth.Substring(4);
            bf |= BindingFlags.SetProperty;
        }
        if (meth.StartsWith("get_"))
        {
           // get the value...
            meth = meth.Substring(4);
            var key = String.Format("{0}_{1}_{2}",
                                    typeof (T).Name,
                                    meth,
                                    typeof (T).GetProperty(meth, BindingFlags.Public | BindingFlags.Instance
        |BindingFlags.GetProperty).
        GetValue(obj, null));
            // but use it for a localized lookup (rm is the ResourceManager)
            var val = rm.GetString(key);
            // return the localized value
            return new ReturnMessage(val, null, 0, null, null);
        }
        var args = new object[0];
        if (msg.Properties["__Args"] != null)
        {
            args = (object[]) msg.Properties["__Args"];
        }
        var res = typeof (T).InvokeMember(meth, 
            bf
            , null, obj, args);
        return new ReturnMessage(res, null, 0, null, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

真实/透明代理使用

 var f = new FooEntity();
 f.Name = "Dutch";
 var l = new Localizer<FooEntity>(f);
 var fp = (FooEntity) l.GetTransparentProxy();
 fp.Name = "Dutch"; // notice you can use the proxy as is,
                    // it updates the actual FooEntity
 var localizedValue = fp.Name;
Run Code Online (Sandbox Code Playgroud)