前面的一些注释:
- 我的回答更多的是补充我对这个问题的回答 https://stackoverflow.com/a/929430/19635,您在其中添加了一条评论,然后引发了这个问题
- 在我的回答中,我使用 C# 和 MS SQL Server(并且我将省略任何 OR 映射特定代码)
在我的应用程序中,我根据用例使用两种不同的方法来加载多语言数据:
管理/增删改查
在用户输入数据或编辑现有数据(例如带有翻译的产品)的情况下,我使用与您在上面的问题中显示的相同的方法,例如:
public class Product
{
public int ID {get; set;}
public string SKU {get; set;}
public IList<ProductTranslation> Translations {get; set;}
}
public class ProductTranslation
{
public string Language {get; set;}
public bool IsDefaultLanguage {get; set;}
public string Title {get; set;}
public string Description {get; set;}
}
IE。我将让 OR 映射器加载产品实例及其所有附加翻译。然后我迭代翻译并选择需要的翻译。
前端/只读
在这种情况下,主要是前端代码,我通常只是向用户显示信息(最好以用户的语言),我使用不同的方法:
首先,我使用的是不同的数据模型,它不支持/不知道多重翻译的概念。相反,它只是以当前用户的“最佳”语言表示产品:
public class Product
{
public int ID {get; set;}
public string SKU {get; set;}
// language-specific properties
public string Title {get; set;}
public string Description {get; set;}
}
为了加载这些数据,我使用了不同的查询(或存储过程)。例如。加载带有 ID 的产品@Id
在语言中@Language
,我会使用以下查询:
SELECT
p.ID,
p.SKU,
-- get title, description from the requested translation,
-- or fall back to the default if not found:
ISNULL(tr.Title, def.Title) Title,
ISNULL(tr.Description, def.Description) Description
FROM Products p
-- join requested translation, if available:
LEFT OUTER JOIN ProductTranslations tr
ON p.ID = tr.ProductId AND tr.Language = @Language
-- join default language of the product:
LEFT OUTER JOIN ProductTranslations def
ON p.ID = def.ProductId AND def.IsDefaultLanguage = 1
WHERE p.ID = @Id
如果存在该语言的翻译,则会返回所请求语言的产品标题和描述。如果不存在翻译,则将返回默认语言的标题和描述。