Linq to Sql Using a function to set a value - linq

I wanted to get from a database a IEnumerable<T> and within the 'Select' method using a function to return a string value. But I always get back the
'method cannot be translated into a store expression'
error.
I already took a look all the post on Stack Overflow about the error 'LINQ to Entities does not recognize the method .... and this method cannot be translated into a store expression"
The only way that I found to get around this error is apply the function after the query has run.
void Main()
{
int eventId = 17;
IEnumerable<OccurrenceDropDownList> model = Occurrences.Select (s => new OccurrenceDropDownList
{
OccurrenceId = s.OccurrenceId,
Name = s.Name
})
.AsEnumerable()
.Select(m => new OccurrenceDropDownList
{
OccurrenceId = m.OccurrenceId,
Name = m.Name,
Selected = setSelected(m.OccurrenceId, eventId)
}).AsEnumerable();
foreach(var item in model)
{
Console.WriteLine(item.Name + " - id : " + item.OccurrenceId + " " + item.Selected);
}
}
public class OccurrenceDropDownList
{
public int OccurrenceId { get; set; }
public string Name { get; set; }
public string Selected { get; set; }
}
static string setSelected(int occurrence, int selectedid){
if(occurrence == selectedid){
return "selected";
}
return "";
}
Is there any way to apply the function as result of the first query?

It should be simplier:
int eventId = 17;
IEnumerable<OccurrenceDropDownList> model = Occurrences
.Select(s => new OccurrenceDropDownList
{
OccurrenceId = s.OccurrenceId,
Name = s.Name,
//magic ternary if
Selected = (eventId == s.OccurrenceId) ? "selected" : String.Empty
});
That's all. I used ternary if operator that should be translated to SQL.

Related

SELECT result map to entity in Dynamic Linq in Entity Framework Core

I have a Linq query which is selecting 2 columns(that can be any 2 from all columns) dynamically based on some condition.I need to map the query result in to below model irrespective of selected column names
public class FinalModel
{
public string Text { get; set; }
public string Id { get; set; }
}
Currently I am using reflection to map the result in to that model because i am getting some anonymous list of objects and it is working fine, But I want to remove that reflection and need to add the mapping in the select itself, my current implementation is like below
string column1 = "Name" //can be other columns also
string column2 = "Age"
var result = _context.table1
.Select("new ("+ column1 +","+ column2 +")")
.Distinct()
.Take(10) // having more records in table
.ToDynamicList()
.Select(x => new FinalModel()
{
Id = x.GetType().GetProperty(column1).GetValue(x).ToString(),
Text = x.GetType().GetProperty(column2).GetValue(x).ToString(),
});
The above code is working fine but I need to remove the below section
.Select(x => new FinalModel()
{
Id = x.GetType().GetProperty(column1).GetValue(x).ToString(),
Text = x.GetType().GetProperty(column2).GetValue(x).ToString(),
});
Is there any way to remove the refletion and add that model mapping directly inside Select("new (column1,column2)")
Is there any way to add orderBy with Column2 variable?
You can use generic versions of Select and ToDynamicList and OrderBy($"{column2}") for sorting:
var result = _context.table1
.Select<FinalModel>($"new ({column1} as Id, {column2} as Text)")
.Distinct()
.OrderBy("Text")
.Take(10)
.ToDynamicList<FinalModel>();
Or if you want to stick with dynamic:
var result = _context.table1
.Select($"new ({column1}, {column2})")
.Distinct()
.OrderBy($"{column2}")
.Take(10)
.ToDynamicList()
.Select(d => new FinalModel()
{
Id = d[column1].ToString(),
Text = d[column2].ToString(),
})
.ToList();
You need to use .Select<T> instead of just .Select() to make sure that the selected entity the correct type. So in your case you need .Select<FinalModel>.
Use the as cast operator to "rename" the properties from the source-entity to the destination entity (FinalModel)
If you want the result to be typed, also use .ToDynamicList<FinalModel>().
Full example code below:
using System.Linq.Dynamic.Core;
class Program
{
static void Main(string[] args)
{
var myQuery = new[] { new XModel { Age = "1", Name = "n" } }.AsQueryable();
string column1 = "Name";
string column2 = "Age";
var result = myQuery
.Select<FinalModel>("new (" + column1 + " as Id, " + column2 + " as Text)")
.Distinct()
.Take(10)
.ToDynamicList<FinalModel>();
Console.WriteLine(result[0].Id + " " + result[0].Text);
}
public class XModel
{
public string Name { get; set; }
public string Age { get; set; }
}
public class FinalModel
{
public string Text { get; set; }
public string Id { get; set; }
}
}

How could I read one to many linked table using link with Entity Framework?

I am new to Entity Framework and Linq (Visual Studio 2017 - EF 5.0) . Currently, I could read tables without issue but wonder how could I read a linked table.
My current functions do it but sure there is a simple way than two step reading that I have developed.
public override List<CartItem> GetMyCartOrderItems(int UserID)
{
try
{
using (foodorderingdbEntities oMConnection = new foodorderingdbEntities())
{
var oCart = oMConnection.carts.SingleOrDefault(p => p.USER_ID == UserID);
if (oCartItems != null)
{
int CartID = oCart.CART_ID;
var oCartItems = oMConnection.cart_item.Where(p => p.CART_ITEM_CART_ID == CartID);
if (oCartItems != null)
{
List<CartItem> oRecList = new List<CartItem>();
foreach (cart_item oDBrec in oCartItems)
{
CartItem oRec = new CartItem();
oRec.CartID = oDBrec.CART_ITEM_ID;
oRec.CartItemID = oDBrec.CART_ITEM_CART_ID;
oRec.DateTime = oDBrec.CART_ITEM_ADDED_DATE_TIME;
oRec.SystemComments = oDBrec.CART_ITEM_SYSTEM_COMMENTS;
oRecList.Add(oRec);
}
return oRecList;
}
else { return null; }
}
else { return null; }
}
}
catch (Exception ex)
{
//IBLogger.Write(LOG_OPTION.ERROR, "File : MHCMySQLDataConection.cs, Method : GetPatientByID(1), Exception Occured :" + ex.Message + Environment.NewLine + "Trace :" + ex.StackTrace);
return null;
}
}
You could see that I get Cart ID from Carts table using UserID and then I use the CartID retrieve cart Items from Cart_Item table. Cart_Item_Cart_ID is a foreign key in cart_item table. (This is a one to many table)
This is what I am thinking but obviously does not work.
List<cart_item> oCartItems = oMConnection.carts.SingleOrDefault(c => c.USER_ID == UserID).cart_item.Where(p => p.CART_ITEM_CART_ID = c.CART_ID).ToList<cart_item>();
Any help ?
My entity relation
public partial class cart
{
public cart()
{
this.cart_item = new HashSet<cart_item>();
}
public int CART_ID { get; set; }
public int USER_ID { get; set; }
public decimal ORDER_TOTAL_COST { get; set; }
public virtual ICollection<cart_item> cart_item { get; set; }
public virtual user user { get; set; }
}
Because your query has multiple levels of one to many relationships, and you just want the cart_items, it's easier to go the other way like this:
var oCart = oMConnection.cart_item
.Where(c=>c.cart.user.USER_ID == UserID);
Going the way you did should have worked as well, but you needed to use SelectMany instead of select like this:
var oCartItems = oMConnection.carts
.Where(c=>c.USER_ID==UserID)
.SelectMany(c=>c.cart_item);

How to convert LINQ query result to list and return generic List?

I used generic ORM list
example.
This is my table.
Person table
Guid
Name
LastName
and this is my struct class.
public struct PersonItem // database and class field names are the same
{
public Guid Guid{ get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public struct PersonItems
{
public PersonItems()
{
Items = new List<PersonItem>();
}
public List<PersonItem> Items { get; set; }
}
I'm using such and no problem but I always have to write field's
public PersonItems GetPersons()
{
var query = (from p in _DbEntities.t_Crew
select p).ToList();
if (query != null)
{
foreach (var item in query)
{
_PersonItems.Items.Add(new PersonItem
{
Guid = item.Guid,
Name = item.Name,
LastName = item.LastName
});
}
}
return _PersonItems;
}
public PersonItems GetPersons()
{
PersonItems personItems = new PersonItems();
var query = from p in _DbEntities.t_Person
select p; >> this here query I need to convert linq query result to list
personItems = query.ToList();
return personItems ;
}
error
Cannot implicitly convert type System.Collections.Generic.List' to PersonData.PersonItems'.
Try this
public PersonItems GetPersons()
{
PersonItems personItems = new PersonItems();
var query = (from p in _DbEntities.t_Person
select new PersonItems
{
test = p.SomeName,
//Other Stuff
//...
}).ToList();
return query;
}
Comparing to the other version of your GetPersons() method, I think this line :
personItems = query.ToList();
should've been this way instead :
personItems.Items = query.ToList();
Update regarding the latest error. You can't assign list of t_Person to Item property which is of type list of PersonItem. Hence, your query need to be adjusted to return list of PersonItem :
var query = from p in _DbEntities.t_Person
select new PersonItem
{
Guid = p.Guid,
Name = p.Name,
LastName = p.LastName
};
or other option is to change definition of Item property to list of t_Person :
public List<t_Person> Items { get; set; }
Cannot implicitly convert type System.Collections.Generic.List' to PersonData.PersonItems'
Above error says that you are trying to convert generic list to PersonItems.
So at this line, query.ToList() code returns List<PersonItem> not the PersonItems
var query = from p in _DbEntities.t_Person
select p; >> this here query I need to convert linq query result to list
personItems = query.ToList();
return personItems ;
So thats the reason above line of code fails.
What about this?
Change .ctor of PersonItems:
public struct PersonItems
{
public PersonItems(List<PersonItem> items)
{
Items = items;
}
public List<PersonItem> Items { get; set; }
}
And then method GetPersons():
public PersonItems GetPersons()
{
return new PersonItems(_DbEntities.t_Person.ToList());
}

Selecting From Dynamic Attribute ASP.NET MVC3

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)
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.
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.
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();
}

Building a query (LINQ) with a sub-query

For simplicity sake lets assume I have the following two classes:
public class ComplexClass
{
public List<SubClass> SubClasses { get; set; }
public string Name { get; set; }
}
public class SubClass
{
public string Name { get; set; }
}
I have a List<ComplexClass> and I need to build a query based on some parameters.
It's an easy task if all I need to do is use the Name property of ComplexClass. Here's an example:
static IQueryable<ComplexClass> GetQuery(string someParameter, string someOtherParameter)
{
var query = list.AsQueryable();
if (!String.IsNullOrEmpty(someParameter))
query = query.Where(c => c.Name.StartsWith(someParameter));
if (!String.IsNullOrEmpty(someOtherParameter))
query = query.Where(c => c.Name.EndsWith(someOtherParameter));
return query;
}
Based on the parameters I have I can add more query elements. Of course the above example is simple, but the actual problem contains more parameters, and that number can grow.
Things aren't as simple if I want to find those ComplexClass instances which have SubClass instances which meet criteria based on parameters:
static IQueryable<ComplexClass> GetSubQuery(string someParameter, string someOtherParameter)
{
var query = list.AsQueryable();
if (!String.IsNullOrEmpty(someParameter))
if (!String.IsNullOrEmpty(someOtherParameter))
return query.Where(c => c.SubClasses.Where(sc => sc.Name.StartsWith(someParameter) && sc.Name.EndsWith(someOtherParameter)).Any());
else
return query.Where(c => c.SubClasses.Where(sc => sc.Name.StartsWith(someParameter)).Any());
else
if (!String.IsNullOrEmpty(someOtherParameter))
return query.Where(c => c.SubClasses.Where(sc => sc.Name.EndsWith(someOtherParameter)).Any());
else
return null;
}
I can no longer just add bits of the query based on each parameter, I now need to write the whole query in one go, and this means I need to check every combination of parameters, which is hardly ideal.
I suspect the key is to build an Expression class and create a lambda expression from that, but I'm not sure how to tackle the problem.
Any suggestions? :)
EDIT:
My initial idea was this:
static IQueryable<ComplexClass> GetSubQuery(string someParameter, string someOtherParameter)
{
var query = list.AsQueryable();
query = query.Where(c =>
{
var subQuery = c.SubClasses.AsQueryable();
if (!String.IsNullOrEmpty(someParameter))
subQuery = subQuery.Where(sc => sc.Name.StartsWith(someParameter));
if (!String.IsNullOrEmpty(someOtherParameter))
subQuery = subQuery.Where(sc => sc.Name.EndsWith(someOtherParameter));
return subQuery.Any();
});
return query;
}
This works in my small console test application as it's using LINQ to Objects. Unfortunately, I need to use Entity Framework and LINQ to Entities, which causes an implementation similar to the one above to throw a A lambda expression with a statement body cannot be converted to an expression tree error message.
I'm assuming that in you real-life code the SubClasses property is IQueryable<SubClass> rather than List<SubClass>?
If so, then your query building becomes easy:
static IQueryable<ComplexClass> GetSubQuery(
string someParameter, string someOtherParameter)
{
var query = list.AsQueryable();
if (!String.IsNullOrEmpty(someParameter))
query = query.Where(c => c.SubClasses
.Where(sc => sc.Name.StartsWith(someParameter)).Any());
if (!String.IsNullOrEmpty(someOtherParameter))
query = query.Where(c => c.SubClasses
.Where(sc => sc.Name.StartsWith(someOtherParameter)).Any());
return query;
}
Mixing IEnumerable<T> and IQueryable<T> using AsQueryable() is never a good idea.
I implemented my solution in a simple Console Project:
internal class Program
{
#region Constants and Fields
private static readonly List<ComplexClass> list = new List<ComplexClass>
{
new ComplexClass
{
Name = "complex",
SubClasses = new List<SubClass>
{
new SubClass
{
SubName = "foobar"
}
}
},
new ComplexClass
{
Name = "complex",
SubClasses = new List<SubClass>
{
new SubClass
{
SubName = "notfoobar"
}
}
}
};
#endregion
#region Public Methods
public static void Main(string[] args)
{
Console.WriteLine("foo / bar :");
GetSubQuery("foo", "bar");
Console.WriteLine();
Console.WriteLine("foo / null :");
GetSubQuery("foo", null);
Console.WriteLine();
Console.WriteLine("string.Empty / bar :");
GetSubQuery(string.Empty, "bar");
Console.WriteLine();
Console.WriteLine("maeh / bar :");
GetSubQuery("maeh", "bar");
Console.ReadKey();
}
#endregion
#region Methods
private static void GetSubQuery(string startsWith,
string endsWith)
{
var query = from item in list
let StartIsNull = string.IsNullOrEmpty(startsWith)
let EndIsNull = string.IsNullOrEmpty(endsWith)
where
(StartIsNull || item.SubClasses.Any(sc => sc.SubName.StartsWith(startsWith)))
&& (EndIsNull || item.SubClasses.Any(sc => sc.SubName.EndsWith(endsWith)))
select item;
foreach (var complexClass in query)
{
Console.WriteLine(complexClass.SubClasses.First().SubName);
}
}
#endregion
public class ComplexClass
{
#region Public Properties
public string Name { get; set; }
public List<SubClass> SubClasses { get; set; }
#endregion
}
public class SubClass
{
#region Public Properties
public string SubName { get; set; }
#endregion
}
}
The Console Output is:
foo / bar :
foobar
foo / null :
foobar
string.Empty / bar :
foobar
notfoobar
maeh / bar :

Resources