GetValue LINQ Error - c#

I'm trying to retrieve the value for a particular property of an entity into a variable using the following code.
var item = db.Notices
.Where(a => a.ID == 0)
.Select(x => x
.GetType()
.GetProperty("Spell_ID")
.GetValue(x));
I'm just playing around with this at the moment, but at some point I'd like to be able to replace the 'Spell_ID' text with any column name and get the value dynamically. Not sure if I'm going the right way around this, but I'm getting the following error:-
LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression.
I know I'm not doing this the right way (and I'm relatively new to C# MVC / LINQ), but I've spent so much time tinkering with the code I've lost my way...can somebody point me in the right direction please?

Your current code uses reflection to get the value of a property, but, from what I can infer from your exception message, db is an Entity Framework DbContext.
Entity framework does not support reflection at all, because your LINQ query is then converted into a SQL query by the framework itself. For this reason you have to change your approach if you really need to get a single property:
var items = db.Notices.Where(a => a.ID == 0).ToList();
var itemsProperty = items.Select(x => x.GetType().GetProperty("Spell_ID"));
This will fetch all the resources from the database and then execute the Select part in memory.
If you expect only a single entity from your database than this is a better approach:
var entity = db.Notices.SingleOrDefault(a => a.ID == 0);
var property = entity.GetType().GetProperty("Spell_ID");

Not to be tounge-in-cheek, but the error
LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression.
is exactly what it sounds like. LINQ is unable to translate the GetValue() method to whatever it is that Entity Framework does exactly.
While there are ways to get EF and LINQ to recognize methods, its kinda a pain. The quickest solution would be to just use a loop.

Related

C# Join two tables using Include. Data comes from a Model

I am very new with C# and need some help. I am working on someone elses code and they are pulling data from a Model. I am trying to join two tables and need to use Include but the error is '==' cannot be applied to Guid and IQueryable. Could someone help with this please. Thanks in advance!
Yes, I am.
.Where() represents your filter. .Select() represents what you want back. If you just want the entities back you don't need a .Select().
If you have an association between menu items and MenuItemProgramData, for example, a MenuItem holds a reference to a MenuItemProgramData then you don't even need the first ID select statement:
return context.DbMenuItems
.Where(x => x.MenItemsProgramData.Plu == plu);
Note: If your context defines DbSet<T> for your various top level entities, you can just use context.Ts rather than .GetItems<T>.
If the relationship exists then this is the preferred approach. Let SQL do the work. The consumer of your method can further .Select() the applicable data, sort it, paginate it, and even append .Include() if you do want to interact with the entire entity graph.
If you don't have a relationship between the menu item and that program data, and know that the # of item IDs from the first query will remain relatively small (say, sub-100) then:
var itemIds = context.DbMenuItemProgramDatas
.Where(x => x.Plu == plu)
.Select(x => x.MenuItemId)
.ToList();
Without the .ToList() you are dealing with an IQueryable which EF would potentially still attempt to translate to SQL statements when later consumed. By using .ToList() it will execute the SQL and populate a List<int>. (Assuming the menu item ID is an int)
To get the IQueryable menu item data rows:
return context.DbMenuItems
.Where(x => itemIds.Contains(x.Id));
And that is it.
Edit: Based on the comment "I want to return a field named ParentId to know if it is empty or not. That's all but I need both tables linked to get that answer."
Additionally, looking back at the original code, the naming of the method is a bit misleading. GetItemProgramDataForSubItems implies returning MenuItemsProgramData rather than MenuItems... However, if ParentId is a property of MenuItem, then the caller of this method can use:
var hasParentId = context.GetItemProgramDataForSubItems(plu)
.Any(x => x.ParentId.HasValue);
If the ParentId is on the MenuItemsProgramData:
var hasParentId = context.GetItemProgramDataForSubItems(plu)
.Any(x => x.MenuItemsProgramData.ParentId.HasValue);
Beyond that, you may want to elaborate on what your entities and relationships look like, and what exactly you aim to accomplish from your method or business logic.

Can't add calculated value to IQueryable

I'm running an EF statement where I need to calculate de deductibles. After long trying, I can't seem to add a custom function in a .Select() statement. Instead I'm trying to add the values after my .Select() statement.
The problem here is, in my CalculateDeductibles() I can't seem to add any values to item.Deductibles.
The GetDeductibles(item.RequestId) is a rather heavy funtion that does several extra queries, so I'm trying to prevent to convert my IQueryable to an IList object.
So there are actually 2 questions:
Can I have the GetDeductibles() function directly in my .Select() statement?
Can I somehow (with keeping an eye on performance) add the value after I did my .Select()
Code:
public IQueryable<ReinsuranceSlip> GetReinsuranceSlipsOverview(int userId, int companyId, string owner, string ownerCompany)
{
IQueryable<ReinsuranceSlip> model = null;
model = _context.Request
.Where(w => w.RequestGroup.ProgramData.MCContactId == userId)
.Select(x => new ReinsuranceSlip()
{
Id = x.Id,
RequestId = x.Id,
LocalPolicyNumber = x.LocalPolicyNumber,
BusinessLine = x.RequestGroup.ProgramData.BusinessLine.DisplayName,
BusinessLineId = x.RequestGroup.ProgramData.BusinessLine.Id,
ParentBroker = x.RequestGroup.ProgramData.Broker.Name,
LocalBroker = x.Broker.Name,
InceptionDate = x.InceptionDate,
RenewDate = x.RenewDate,
//Deductibles = CalculateDeductibles(x)
});
CalculateDeductibles(model);
return model;
}
private void CalculateDeductibles(IQueryable<ReinsuranceSlip> model)
{
//model.ForEach(m => m.Deductibles = GetDeductibles(m.RequestId));
foreach (var item in model)
{
item.Deductibles = GetDeductibles(item.RequestId);
}
}
Updated and Sorry for the first version of this answer. I didn't quite understand.
Answer 1: IQueryable is using to creating a complete SQL statement to call in SQL Server. So If you want to use IQueryable, your methods need to generate statements and return it. Your GetDetuctibles method get request Id argument but your queryable model object didn't collect any data from DB yet, and it didn't know x.Id value. Even more, your GetCarearDetuctiples get an argument so and with that argument generates a queryable object and after some calculations, it returns decimal. I mean yes you can use your methods in select statement but it's really complicated. You can use AsExpendable() LINQ method and re-write your methods return type Expression or Iqueryable.
For detailed info you should check. This:
Entity Navigation Property IQueryable cannot be translated into a store expression and this: http://www.albahari.com/nutshell/predicatebuilder.aspx
And you also should check this article to understand IQueryable interface: https://samueleresca.net/2015/03/the-difference-between-iqueryable-and-ienumerable/
Answer 2: You can use the IEnumerable interface instead IQueryable interface to achieve this. It will be easy to use in this case. You can make performance tests and improve your methods by time.
But if I were you, I'd consider using Stored Procedures for performance gain.
You'll have to understand the differences between an IEnumerable and an IQueryable.
An IEnumerable object holds everything to enumerate over the elements in the sequence that this object represents. You can ask for the first element, and once you've got it, you can repeatedly ask for the next element until there is no more next element.
An IQueryable works differently. An IQueryable holds an Expression and a Provider. The Expression is a generic description of what data should be selected. The Provider knows who has to execute the query (usually a database), and it knows how to translate the Expression into a format that the Provider understands.
There are two types of LINQ functions: the ones that return IQueryable<TResult> and the ones that return TResult. Functions form the first type do not execute the query, they will only change the expression. They use deferred execution. Functions of the second group will execute the query.
When the query must be executed, the Provider takes the Expression and tries to translate it into the format that the process that executes the query understand. If this process is a relational database management system this will usually be SQL.
This translation is the reason that you can't add your own functionality: the Expression must be translatable to SQL, and the only thing that your functions may do is call functions that will change the Expression to something that can be translated into SQL.
In fact, even entity framework does not support all LINQ functionalities. There is a list of Supported and Unsupported LINQ methods
Back to your questions
Can I have GetDeductibles directly in my query?
No you can't, unless you can make it thus simple that it will only change the Expression using only supporte LINQ methods. You'll have to write this in the format of an extension function. See extension methods demystified
Your GetDeductibles should have an IQueryable<TSource> as input, and return an IQueryable<TResult> as output:
static class QueryableExtensions
{
public static IQueryable<TResult> ToDeductibles<TSource, TResult, ...>(
this IQueryable<TSource> source,
... other input parameters, keySelectors, resultSelectors, etc)
{
IQueryable<TResult> result = source... // use only supported LINQ methods
return result;
}
}
If you really need to call other local functions, consider calling AsEnumerable just before calling the local functions. The advantage above ToList is that smart IQueryable providers, like the one in Entity Framework will not fetch all items but the items per page. So if you only need a few ones, you won't have transported all data to your local process. Make sure you throw away all data you don't need anymore before calling AsEnumerable, thus limiting the amount of transported data.
Can I somehow add the value after I did my .Select()
LINQ is meant to query data, not to change it. Before you can change the data you'll have to materialize it before changing it. In case of a database query, this means that you have a copy of the archived data, not the original. So if you make changes, you'll change the copies, not the originals.
When using entity framework, you'll have to fetch every item that you want to update / remove. Make sure you do not select values, but select the original items.
NOT:
var schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
.Select(school = new
{
... // you get a copy of the values: fast, but not suitable for updates
})
.FirstOrDefault();
BUT:
School schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
.FirstOrDefault()
Now your DbContext has the original School in its ChangeTracker. If you change the SchoolToUpdate, and call SaveChanges, your SchoolToUpdate is compared with the original School, to check if the School must be updated.
If you want, you can bypass this mechanism, by Attaching a new School directly to the ChangeTracker, or call a Stored procedure.

Can't do cast in LINQ with IQueryable?

I'm wondering how to get the query below to work:
IQueryable<TypeA> data = ...;
data = data.OrderBy(x => ((TypeB)x.RelatedObject).Value);
The error I get is:
The specified type member 'RelatedObject' is not supported in LINQ to
Entities. Only initializers, entity members, and entity navigation
properties are supported.
I'm very new to C#, I think this is a compile problem because I know RelatedObject is of TypeB.
Thanks!
Apparently, Entity Framework does not know (enough) about the relation between TypeA and TypeB. If you can define it as a navigation property, that would solve your problem.
If that is not possible, inserting .AsEnumerable() should work:
data.AsEnumerable().OrderBy(x => ((TypeB)x.RelatedObject).Value);
What this will do, is having 'normal' LINQ performing the ordering, instead of the database (with an ORDER BY clause in the SQL query). Note that it returns an IEnumerable<TypeA> instead of an IQueryable<TypeA> - depending on what you do with this variable, this might cause more records to be loaded into memory than strictly necessary.
If you know that you're only getting one specific type, you should be able to do something like this, assuming that EF knows about the inheritance.
IQueryable<TypeA> data = ...;
data = data.OfType<TypeB>().OrderBy(x => (x.RelatedObject).Value);

The method 'Where' cannot follow the method 'Select' or is not supported

Why am I getting:
The method 'Where' cannot follow the method 'Select' or is not
supported. Try writing the query in terms of supported methods or call
the 'AsEnumerable' or 'ToList' method before calling unsupported
methods.
...when using the WHERE clause, like when calling:
XrmServiceContext.CreateQuery<Contact>().Project().To<Person>().Where(p => p.FirstName == "John").First();
?
This works:
XrmServiceContext.CreateQuery<Contact>().Project().To<Person>().First();
Also this works:
XrmServiceContext.CreateQuery<Contact>().Where(p => p.FirstName == "John").First();
I'm using AutoMapper QueryableExtension.
Additional info:
I don't want to call ToList() before the Where clause. I know it will works that way.
CreateQuery<TEntity>() returns IQueryable<TEntity>.
It's because whatever query provider you are using isn't able to handle this. It's not invalid in the general case; in fact most query providers do support filtering after projecting. Certain query providers simply aren't as robust as others, or they are representing a query model that is less flexible/powerful than the LINQ interface (or both). As a result, LINQ operations that are correct from the C# compiler's point of view might still not be translatable by the query provider, so the best it can do is throw an exception at runtime.
Why don't you just move the where so it is before the projection? It will result in a single query being executed which filters and projects:
XrmServiceContext.CreateQuery<Contact>().Where(p => p.FirstName == "John").Project().To<Person>().First();
Looking at AutoMapper's instructions for the QueryableExtensions it has an example showing the Where clause before the projection. You need to refactor your code to support this model, as opposed to placing the Where clause after the projection.
public List GetLinesForOrder(int orderId)
{
Mapper.CreateMap()
.ForMember(dto => dto.Item, conf => conf.MapFrom(ol => ol.Item.Name);
using (var context = new orderEntities())
{
return context.OrderLines.Where(ol => ol.OrderId == orderId)
.Project().To().ToList();
}
}
Given the limitations of Dynamic CRM's LINQ provider you should not expect AutoMapper to necessarily get the LINQ query correct.
There is actually a logic behind this design. As the developer you create a working Where clause. You then let AutoMapper's Project().To() define the select statement. Since CRM's LINQ provider has support for anonymous types in it should work correctly. The purpose of projection in AutoMapper is to limit the data retrieved from each class to only that needed for the projected to class. It is not intended to write a Where clause based on the projected to class.

Text search on Generic type in Entity Framework

I'm trying to implement a text search for database tables. I've a generic repository and don't really want to have to create derived ones for every model I might want to expose because there are quite a few in the database.
So the code I'm having difficulty with is as follows:
var props = typeof(T).GetProperties()
.Where(p => p.PropertyType == typeof(string));
IEnumerable<T> searched = null;
if (!string.IsNullOrWhiteSpace(searchTerm))
searched = sorted.Where(c => props
.Select(p => (string)p.GetValue(c, null))
.Select(v => v.Contains(searchTerm))
.Contains(true));
I'm feeding this a collection of PropertyInfo's obtained through a little reflection. Possibly not a high performance idea but I've yet to think of a better way. So these might be all properties of type string (searching all strings in the table) or it might be pulling certain properties in the model that have a custom Searchable attribute.
The runtime exception I'm getting is:
NotSupportedException: Unable to create a constant value of type 'System.Reflection.PropertyInfo'. Only primitive types ('such as
Int32, String, and Guid') are supported in this context.
I can see that I'm using reflection but not quite sure what exactly is causing the exception here. If someone could point this out then that would be much appreciated but if someone could suggest a better way to do this then that would be amazing. Thanks in advance!
The problem is that when the LINQ query is executed, it's trying to construct a SQL query to perform on the database. The exception message indicates that only primitive types can be used in the LINQ query because those are the only types that can be converted successfully into a SQL query.
Hopefully solving your problem, you just need to ensure that the database SQL query executes before extending the LINQ query using non-primitive types.
I'm guessing the sorted variable in your code snippet is a LINQ query, so call sorted.AsEnumerable() to execute the SQL query on the database and then you can perform the search functionality.
searched = sorted.AsEnumerable()
.Where(c => props.Select(p => (string)p.GetValue(c, null))
.Any(v => v.Contains(searchTerm)));

Categories