c# - LINQ dynamic case -
i have method:
private string getlanguage(string currentlanguage, dynamic entity) { return (currentlanguage == "de" ? entity.language.german : currentlanguage == "fr" ? entity.language.french : currentlanguage == "en" ? entity.language.english : entity.language.english); }
and need return linq expression sql statement:
select (case when [french] null [english] else [french] end) language
how can achieve this?
tks
edit:
to more specific:
i have this:
myid = 1; objects in context.objects objects.id== myid select new { myobject = new models.myobjects() { id = objects.scrid, title = languagefactory.getlabellanguage(objects.labels) } }).firstordefault();
and myobject.title must in language (english, french, dutch, etc.). in sql resolved doing like:
select id, (case when [french] null [english] else [french] end) language table
how can linq expression can translated sql query above?
you won't able call arbitrary functions in linq-to-sql. can use expression
, this:
private expression<func<dbobject, myobject>> getobjectwithlanguage = e => new myobject { id = e.scrid, title = e.currentlanguage == "de" ? e.labels.language.german : e.currentlanguage == "fr" ? e.labels.language.french : e.currentlanguage == "en" ? e.labels.language.english : e.labels.language.english }; ... var results = context.objects.where(e => e.id == myid).select(getobjectwithlanguage);
this use currentlanguage
property on entity determine return. however, if want pass currentlanguage
parameter c# code, try this:
private expression<func<dbobject, myobject>> getobjectwithlanguage(string currentlanguage) { if (currentlanguage == "de") { return e => new myobject { id = e.scrid, title = e.labels.language.german } } else if (currentlanguage == "fr") { return e => new myobject { id = e.scrid, title = e.labels.language.french } } ... } var results = context.objects.where(e => e.id == myid).select(getobjectswithlanguage("de"));
if create general purpose method, suggest use generics rather dynamic
parameters, example, suppose have interface like:
public interface ilanguageaware { string currentlanguage { get; } string english { get; } string french { get; } string german { get; } } public class objectwithlanguage<t> t : ilanguageaware { public t originalobject { get; set; } string languagetext { get; set; } } public expression<func<t, objectwithlanguage<t>>> getobjectwithlanguage<t>() t : ilanguageaware { return x => new objectwithlanguage<t> { originalobject = x, languagetext = x.currentlanguage == "de" ? x.german : x.currentlanguage == "fr" ? x.french : ... } } // extension method convenience public static iqueryable<objectwithlanguage<t>> selectwithlanguage<t>(this iqueryable<t> queryable) { return queryable.select(getobjectwithlanguage<t>()); } var results = context.objectss.where(e => e.id == myid).selectwithlanguage();
Comments
Post a Comment