How to Order By Dynamic value via Entity Framework? - c#

I'm building an asp.net mvc app using Entity Framework, and I'm trying to order by a list. By a dynamic changed name, according to the name exists in the database.
bids = bids.OrderBy(s => s.PublisherName);
and the object:
public string PublisherName { get { db.Publishers.Find(pubid).Name; } }
But I'm getting an exception:
The specified type member 'PublisherName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
What can I do? And how I can make it work?
Thanks.

Only initializers, entity members, and entity navigation properties
are supported.
db.Publishers.Find(pubid).Name; is neither initializer nor entity member, nor navigation property.
One possible way is to bring it on memory with AsEnumerable() :
bids = bids.AsEnumerable().OrderBy(s => s.PublisherName);
This will work perfectly as long as bids is small list of objects.

I believe Bidand Publisher are related, right? Maybe this will help you
var bids = from t in context.Bids
let u = t.Publishers.FirstOrDefault(i => i.Id == pubid)
orderby u.Name
select t;
Untested code, not sure if it will work for you!

When using Entity Framework via LINQ, all of the properties in the linq statement are translated in to SQL. EF only natively understands simple properties. It doesn't understand how to translate properties that contain actual code logic, which is what is causing the error you are seeing. The simplest way to fix this is to do the sort client side, outside of entity framework. The usual way to do this is to call .ToList on the unsorted result, and then sort the resulting list, which will happen client side.

Related

Entity Framework Core get entity without related entities

I've been searching a bit on this but thus far haven't been able to find a decent solution. I'm trying to get an entity from my database without the related entities attached to it.
The function goes as following return context.Entity.SingleOrDefault(n => n.Name == name) where context is a DbContext.
As of now the reply contains only one Entity but with an added 50 "child" entities which I do not need.
What would be the best way to go about getting a single entity from the db?
Using EFC2.1 pre release build
Edit:
Also found that if you use DbContext.Entity.AsNoTracking you can get the entity without the child collections.
Not sure if the full entity will be saved after making changes and calling DbContext.saveChanges()
You have to enable Lazy Loading, simply add a property to your class like this.
public virtual ICollection<ChildType> NavigationProperty;
Here is a very useful document for Loading Related Data.
I recently discovered that you can also use DbContext.Entity.AsNoTracking() for this purpose.
Using a linq query when fetching an entity will cause all related entities contained in the linq to also be fetched.
Say you have a Teacher, a Student and a Classroom entity. A Teacher can have multiple Students and Classrooms. You want to find all Teachers with classroom A and all male students so you would do
DbContext.Teachers.Where(x => x.Classroom.Name = "A" && x.Student.Gender = "Male")
This will fetch the Teacher entities with all underlying Classrooms and Students since you called on them in the linq expression.
Since you want just the Teacher entity you should use the following :
DbContext.Teachers.AsNoTracking().Where(x => x.Classroom.Name = "A" && x.Student.Gender = "Male")
Using AsNoTracking() you declare that you do not want the underlying data and just need it to filter through the entity you do want.

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);

Creating a property that LINQ to Entities can translate

I am curious on how to create a property that can be translated by LINQ. Below is a very simple example.
I have a table/class Category, that has a column ParentId linking to itself (So a category can have sub-categories)
EF automatically generates a property Category1, which is the parent category.
For the sake of clarity, I created another property
public partial class Category
{
public Category Parent
{
get { return Category1; }
}
}
The problem is, this works
var categs = ctx.Categories.Where(x => x.Category1 == null);
but this doesn't work
var categs = ctx.Categories.Where(x => x.Parent == null);
The specified type member 'Parent' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Is there any way to create a translatable property (LINQ to SQL) without doing .ToList()?
EDIT: I want to avoid touching Model.edmx because the database often changes during development and the .edmx often needs to be recreated
If you ask if it's possible to create a property with any C# code in the getters/setters and later have it understood by standard LINQ to Entities - then no, it can't be done. C# is much more expressive then SQL and it's unreasonable to expect Entity Framework to act as a general C# to SQL translator.
You can work around this is many cases though, see Using a partial class property inside LINQ statement for an example.
Update
It'd help if you told us what exactly you want to achieve, but here's an example:
public partial class Category
{
public static Expression<Func<Category, bool>> ParentIsNullExpression
{
get
{
return c => c.Category1 == null;
}
}
}
And then
var categs = ctx.Categories.Where(Category.ParentIsNullExpression);
All sorts of manipulations on Expressions are possible, some of them are supported by EF and as such translate to SQL.
in your Entity Data Model Designer (.edmx file), you can rename the Category1 to Parent
You have 4 options:
Use code first
Add it to the EDMX designer
Add your property to the CSDL section of the EDMX, add a column to the SSDL section of the EDMX, then map them to each other in the mapping section of the EDMX.
Bring the query into memory using .ToList() then use internal LINQ instead of LINQ to Entities.

Can Dynamic LINQ be made compatible with Entity Complex Types?

I want to dynamically query an object with System.Linq.Dynamic.
var selectData = (from i in data
select i).AsQueryable().Where("Name = #0","Bob1");//This works fine with a non-entity object
I know that we cannot project onto a mapped entity. I believe that is the reason this code fails
foreach (var item in rawQuery.ObsDataResultList)
{
var propertyData = (from i in item
select i).AsQueryable().Where("PropertyName = #0", "blah");
}//item is a Entity Complex Type
Error
Could not find an implementation of the query pattern for
source type 'ClassLibrary1.Model.bhcs_ObsData_2_Result'. 'Select' not
found.
Given the fact that I need to specify the PropertyName at runtime, I don't see any way to project with an anonymous type or a DTO.
I don't need to retain any of the Entity functionality at this point, I just need the data. Copying the data onto something that is queryable is a valid solution. So, is it possible to query entity framework with dynamic LINQ?
And here is the entity class header (the thing I'm trying to query, aka the item object)
[EdmComplexTypeAttribute(NamespaceName="MyDbModel", Name="blah_myQuery_2_Result")]
[DataContractAttribute(IsReference=true)]
[Serializable()]
public partial class blah_myQuery_2_Result : ComplexObject
{
First of all, let me clarify that System.Linq.Dynamic is not a full fledged Microsoft product. It is just a sample we release some time ago, and we don't thoroughly test different LINQ implementations to work correctly with it. If you are looking for a fully supported text-based query language for EF ObjectContext API you should take a look at Entity SQL instead.
Besides that, if you want to use System.Linq.Dynamic and you are ok with testing yourself that you don't hit anything that will block your application from working, then I'll try to see if I can help. I am going to need additional information since I am not sure I understand everything in your code snippets.
First of all I would like to understand, in your first example what is "data" and where did it come from? In your second snippet, what is "rawQuery" and where did it come from? Besdies, what is rawQuery.DataResultList and what is rawQuery.ObsDataResultList?
Also regarding your second snippet, it seems that you are trying to compose with query operators on top of an object that is not actually of a query type (although that doesn't explain the error you are getting given that you are calling AsQueryable the compiler should have complained before that bhcs_ObsData_2_Result is not an IEnumerable nor a non-generic IEnumerable).
In your propposed answer you are saying that you tried with ObjectResult and that seemed to help. Just be aware that ObjectResult is not a query object and therefore it won't allow you to build queries that get send to the server. In other words, any query operators that you apply to ObjectResult will be evaluated in memory and if you don't keep this in mind you may end up bringing all the data from that table into memory before you apply any filtering.
Query ObjectResult<blah_myQuery_2_Result> directly instead of the item blah_myQuery_2_Result. For example
var result = (from i in rawQuery.DataResultList
select i).AsQueryable().Where("CreatedDTM > #0", DateTime.Now.Subtract(new TimeSpan(30, 0, 0, 0)));

Self join not including children (entity framework 4.0)

I am creating a sort of family tree in entity framework 4.0. I have come across an issue where the Entity Framework is only loading the immediate children. It does not load the children of the children even though i have an include specified.
For example, this is my query :-
public IQueryable<TreeMember> GetTreeMembers(int userId)
{
return this.ObjectContext.TreeMembers.Include("RelatedTreeMembers").Where(u => u.UserId == userId && u.RelatedTreeMemberId == null);
}
This would load the 1st level of children. But it does not load the children of the children. If i have to include children of the children, i have to write :-
public IQueryable<TreeMember> GetTreeMembers(int userId)
{
return this.ObjectContext.TreeMembers.Include("RelatedTreeMembers.RelatedTreeMembers").Where(u => u.UserId == userId && u.RelatedTreeMemberId == null);
}
This is quickly getting to be frustrating because i don't know how many times should i have to write this RelatedTreeMembers as a family tree can extend upto N level. How do i get past this issue? If my question is not clear please let me know.
Thanks in advance :)
That is how EF works. You want to define recursive (hierarchical) query which is not possible with eager loading in EF. You always have specify exactly which navigation properties you want to load - obviously in this scenario you can't because you don't know how deep is your recursion.
I like the idea #Magnus suggested with CTE but I would not use DB View. I would use stored procedure. The reason is that you already have entity TreeMember mapped to a table. If you define the view you will not be able to map it to the same entity type. You will need new entity for the view. If you use stored procedure you can map its result to already existing entity type.
Another way is to use lazy loading.
Write a view with a recursive CTE and than use that with Linq.
http://msdn.microsoft.com/en-us/library/ms186243.aspx

Categories