如何在EF Core中有效地对可翻译属性建模? [英] How can I effectively model Translatable Properties in EF Core?

查看:39
本文介绍了如何在EF Core中有效地对可翻译属性建模?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building an application on .NET 5 using Entity Framework Core and PostgreSQL. In the database, I have several entities that contain string properties that should be translatable to different languages.

我目前的做法是:

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; }
    }

并带有示例用法,例如:

and with an example usage like:

    public class Product
    {
        public int Id { get; set; }
        
        public int NameId { get; set; }
        
        public virtual TString Name { get; set; }
  
        [...]
    }

以上方法有效,但是对我来说似乎很模糊,因为查询时总是需要使用 .Include(x => x.Name).ThenInlude(n => n.Translations)除非您使用Owned Types(除非拥有类型),否则无法告诉EF Core默认加载属性(这不是一个选择,因为那样便无法使用TString Id进行查询),有没有更好的方法呢?

The approach above works, but seems very unelegant to me since when querying, it is always necessary to use .Include(x => x.Name).ThenInlude(n => n.Translations) Since there is no way to tell EF Core to load a property by default unless you are using Owned Types (which is not an option because then you cannot query using the TString Id), is there any better way of doing this?

推荐答案

因为除非您使用拥有的类型",否则默认情况下无法告诉EF Core加载属性

Since there is no way to tell EF Core to load a property by default unless you are using Owned Types

实际上是-从EF Core 5.0开始,通过 AutoInclude 流利的API,例如

Actually there is - starting from EF Core 5.0, by configuring navigation properties using the AutoInclude fluent API, like

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

modelBuilder.Entity<TString>()
    .Navigation(e => e.Translations)
    .AutoInclude();

这篇关于如何在EF Core中有效地对可翻译属性建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆