我使用表格"TLanguage"来记录我网站的可标记结果。我在这个表中有4列:法语、英语、德语和西班牙语。
在MVC应用程序中,我使用这个查询:
var req = (from TYP in context.TYP_TypeMission
join ML in context.TLanguage on TYP.IDTMultiLanguage equals ML.IDTMultiLanguage
where TYP.IDTFiliale == idFiliale
orderby TYP.LibTypeMission
select new SelectListItem
{
Selected = TYP.IdTypeMission == idTypeMission,
Value = SqlFunctions.StringConvert((double)TYP.IdTypeMission),
Text = ML.French
}).ToList();
如何根据我的网站语言在查询中将ml .法语改为ml .英语或ml .德语?
是否可以在查询中创建间接?
可以这样对映射进行参数化:
public class TLanguageMap : EntityTypeConfiguration<TLanguage>
{
public TLanguageMap(string language)
{
this.HasKey(t => t.TLanguageId);
this.Property(t => t.Translation).HasColumnName(language);
}
}
在上下文中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TLanguageMap(this._language));
}
及其构造函数:
public LocalizableContext(string language)
{
this._language = language;
}
现在,当构建上下文时,您可以确定它适用于哪种语言:
var context = new LocalizableContext("French");
查询将始终是:
...
select new SelectListItem
{
Selected = TYP.IdTypeMission == idTypeMission,
Value = SqlFunctions.StringConvert((double)TYP.IdTypeMission),
Text = ML.Translation
})
您可能希望通过使用enum
语言和switch
语句来获得数据库列名来使其更健壮。
您可以将查询的开头保存为变量,稍后只更改最后一部分:
var query = from TYP in context.TYP_TypeMission
join ML in context.TLanguage on TYP.IDTMultiLanguage equals ML.IDTMultiLanguage
where TYP.IDTFiliale == idFiliale
orderby TYP.LibTypeMission
select new { ML, TYP };
List<SelectListItem> req;
if(Site.Lang == "DE")
{
req = (from item in query
select new SelectListItem
{
Selected = item.TYP.IdTypeMission == idTypeMission,
Value = SqlFunctions.StringConvert((double)item.TYP.IdTypeMission),
Text = item.ML.German
}).ToList();
}
else if(Site.Lang == "FR")
{
req = (from item in query
select new SelectListItem
{
Selected = item.TYP.IdTypeMission == idTypeMission,
Value = SqlFunctions.StringConvert((double)item.TYP.IdTypeMission),
Text = item.ML.French
}).ToList();
}
else
{
req = (from item in query
select new SelectListItem
{
Selected = item.TYP.IdTypeMission == idTypeMission,
Value = SqlFunctions.StringConvert((double)item.TYP.IdTypeMission),
Text = item.ML.English
}).ToList();
}
查询不会执行,直到ToList()
被调用。