Reputation: 5447
I'm developing an ASP.NET MVC3 project which has multi-language support. I hold all the words in database and select from it according to a Session value. At present I get the value as the following:
public ActionResult Index()
{
string lang = (string)System.Web.HttpContext.Current.Session["Language"];
if (lang == "Tr" || lang == null)
{
ViewBag.Admin = db.Words.Find(10).Tr;
}
else if(lang == "En")
{
ViewBag.Admin = db.Words.Find(10).En;
}
return View();
}
The present type of Word:
public class Word
{
public int ID { get; set; }
public string Tr { get; set; }
public string En { get; set; }
}
However, the number of languages will raise, and with the present method I need to add these by hand. What I want is getting the word's "Session" language form dynamically such as (in pseudo):
ViewBag.Admin = db.Words.Find(10)."Session[Language]";
I know it should be easy but couldn't find the appropriate keywords to find this. Any idea how can I achieve this?
EDIT: I just need a way to execute an SQL String like the following:
String lang = (string)System.Web.HttpContext.Current.Session["Language"];
ViewBag.MyWord = ExecuteSQL.("SELECT " + lang + " FROM Words WHERE ID = " + 10 + " ");
EDIT 2: I tried the following lines:
ViewBag.Admin = db.Words.SqlQuery("SELECT" +
(string)System.Web.HttpContext.Current.Session["Language"] +
"FROM Words WHERE ID=10");
However, the output for this is the query itself on the screen. (SELECT Tr FROM Words WHERE ID=10)
Upvotes: 0
Views: 256
Reputation: 2985
You could do it by reflection. Just get the property by the language-key.
Here is some code:
Word word = ...
string lang = (string)System.Web.HttpContext.Current.Session["Language"];
PropertyInfo pi = typeof(Word).GetProperty(lang);
return pi.GetValue(word, null);
I did not at exception handling.
Upvotes: 1
Reputation: 15890
If you are using EF as your ORM you could do something like this:
int wordId = 10;
string lang = (string)System.Web.HttpContext.Current.Session["Language"];
var query = "SELECT " + lang + " FROM Words WHERE ID = {0}";
var word = context.Database.SqlQuery<string>(query, wordId).FirstOrDefault();
See here for more info on raw sql queries:
http://msdn.microsoft.com/en-us/data/jj592907.aspx
NOTE: The above could be open to sql injection, probably best to test that it's a 2 character language code before sending the sql request to the server.
Upvotes: 1
Reputation: 2985
You could use an expression/delegate.
Write a methode returning the expression depending on Session["Language"]
.
private string GetLanguageStringByKey(int key){
return GetFuncByLanguage()(db.Words.Find(key));
}
private Func<Word,string> GetFuncByLanguage(){
string lang = (string)System.Web.HttpContext.Current.Session["Language"];
Func<Word, string> func;
switch(lang){
case "En":{
func = w => w.En;
break;
}
default:{
func = w => w.Tr;
break;
}
}
return func;
}
public ActionResult Index()
{
ViewBag.Admin = GetLanguageStringByKey(10);
return View();
}
Upvotes: 0