.net - 为 dotnet 应用程序存储全球化数据模型的推荐方式
问题描述
我想实现一组数据模型,该模型还将存储其全球化内容,这些内容可以通过请求文化显示在 .NET MVC 和 dotnet 核心应用程序中,但是,我找不到用于此目的的相关资源/关键字,以下是示例模型,任何关键字/建议将不胜感激
public interface Article {
string ArticleId { get; }
string Title { get; }
string Content { get; }
}
public interface CulturedArticle {
string ArticleId { get; }
string Culture { get; } // -- e.g. en or jp
string Title { get; }
string Content { get; }
}
编辑1:
如果我执行以下操作似乎很难看,正在为此目的找到更好的方法
...
var article = this.GetRequestedArticle(request);
var cultureName = this.GetCultureName(request);
var culturedArticle = this.GetCulturedArticle(
article.ArticleId,
cultureName
);
return culturedArticle ?? article;
...
解决方案
以前我使用这种实现一对多关系的方法,其中主实体与多个本地化实体有关系。当您的模型很少时,它很容易实现。但问题是您应该创建所有需要本地化的字段,然后创建自定义控制器/视图来处理每个模型的翻译。如果模型太多,这意味着要做很多工作。
目前我正在测试一种新方法,它更难实现,但当我有太多模型时,我发现它非常灵活。
我没有创建包含所有字段的本地化模型,而是为所有本地化模型创建了一个类似的结构,我只保留属性名称及其本地化值以及一些与主要实体和文化相关的字段。新方法允许只使用一个视图来处理翻译每一种本地实体,因为它们都实现了相同的接口。
下面是我所做的总结。
- 我为可本地化的模型创建了一个接口:
public interface ILocalizedPropertyResource<T>
where T : class
{
// The property name from the main entity
string PropertyName { get; set; }
// Localized content
string Value { get; set; }
int EntityId { get; set; }
T Entity { get; set; }
string CultureName { get; set; }
Culture Culture { get; set; }
}
- 然后我创建了一个名为的自定义属性
[LocalizeAttribute]
,它没有什么特别的,只是将应用于可本地化的实体属性。
[AttributeUsage(AttributeTargets.Property)]
public class LocalizeAttribute : Attribute
{
public LocalizeAttribute() { }
}
- 然后我创建了模型并应用了
Localize
如下属性:
public string Article
{
public int Article { get; set; }
[Localize]
public string Title { get; set; }
[Localize]
public string Content { get; set; }
public ICollection<ArticleLocal> Locals { get; set; }
}
- 然后,创建文章的本地模型:
public class ArticleLocal : ILocalizedPropertyResource<Article>
{
public int Id { get; set; }
// This will hold the localizable property name
// e.g. "Title" or "Content"
public string PropertyName { get; set; }
// This will hold the localized value
public string Value { get; set; }
public int EntityId { get; set; }
public Article Entity { get; set; }
// relation to cultures table
public string CultureName { get; set; }
public Culture Culture { get; set; }
}
- 并且使用反射,我确实检查了具有
[Localize]
属性的属性,以动态创建翻译表单,使用一个视图为所有模型保存值。
因此,使用新方法,我拥有主要实体,以及可以轻松包含和过滤的本地化属性集合。
新方法的工作仍在进行中,但正如开头所述,新方法为我节省了很多时间和精力。
推荐阅读
- if-statement - 如何仅在项目等于或大于 1 时才显示图标子项和文本子项,如果它们为 0 则使它们不可见
- python - 有没有办法更有效地格式化这个字符串?
- python - AWS boto3 - 等到卷附加到 EC2 实例
- python - 如何将参数绑定到 InfluxDB Python 客户端查询
- inno-setup - 如何使用 Inno 检测和安装先决条件?
- r - 按 ID R 识别重叠的日期范围
- python - 字符串的条件行和列替换
- auth0 - 将范围分配给由 Auth0 Manager API 创建的资源服务器
- php - 如何防止 TCPDF 中的分页符
- pandas - 如果条件发生在任何行/列中,则读取 Pandas 数据框