如何在 EF Core 中有效地建模可翻译属性?

fwi*_*erl 3 .net translation entity-framework-core

我正在使用 Entity Framework Core 和 PostgreSQL 在 .NET 5 上构建应用程序。在数据库中,我有几个包含应可翻译为不同语言的字符串属性的实体。

我目前的做法是:

public class TString
    {
        public int Id { get; set; }
        
        /// <summary>
        /// The string value = Default Value
        /// </summary>
        public string Text { get; set; }
        
        public virtual ICollection<Translation> Translations { get; set; }

        /// <summary>
        /// Returns the translation for a given language or the default value.
        /// </summary>
        /// <param name="language"></param>
        /// <returns></returns>
        public string Get(string language)
        {
            if (Translations.Any(t => t.Language == language))
                return Translations.First(t => t.Language == language).Text;
            return Text;
        }
   }

    public class Translation
    {
        public int Id { get; set; }
        
        public int TStringId { get; set; }
        public virtual TString TString { get; set; }
        public string Language { get; set; }
        public string Text { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

并有一个示例用法,例如:

    public class Product
    {
        public int Id { get; set; }
        
        public int NameId { get; set; }
        
        public virtual TString Name { get; set; }
  
        [...]
    }
Run Code Online (Sandbox Code Playgroud)

上面的方法有效,但对我来说似乎非常不优雅,因为在查询时,总是需要使用“ .Include(x => x.Name).ThenInlude(n => n.Translations) Since 没有办法告诉 EF Core 默认加载属性,除非您使用 Owned Types(这不是一个选项,因为那么您无法使用 TString Id 进行查询),有没有更好的方法可以做到这一点?

Iva*_*oev 5

由于除非您使用 Owned Types,否则无法告诉 EF Core 默认加载属性

实际上是有的 - 从 EF Core 5.0 开始,通过使用Fluent API配置导航属性AutoInclude,例如

modelBuilder.Entity<Product>()
    .Navigation(e => e.Name)
    .AutoInclude();

modelBuilder.Entity<TString>()
    .Navigation(e => e.Translations)
    .AutoInclude();
Run Code Online (Sandbox Code Playgroud)