Reputation: 5962
I am trying fetch nested data from Ef query.
var imagePath = ImagePath.GetImagePath();
var data = repos.JobCategoryRepo.GetMany(x => x.Parent == null).Select(x => new JobCategoryModel
{
CategoryName = x.CategoryName,
Identifier = x.Identifier,
ImagePath = x.Images != null ? imagePath+"/"+x.Images.ImagePath : null,
ChildCategories = x.SubCategory.Select(y => new JobCategoryModel
{
CategoryName = y.CategoryName,
Identifier = y.Identifier,
ImagePath = y.Images != null ? imagePath + "/" + y.Images.ImagePath : null,
ChildCategories=null
})
});
And repos.JobCategoryRepo.GetMany(x => x.Parent == null)
will return IQueryable
As I know at second level, There is no ChildCategories, So At second level, I set ChildCategories=null
But Ef query doesn't allow me to assign Null value at this level.
Unable to create a null constant value of type 'System.Collections.Generic.IEnumerable`1[[EntityModel.JobCategoryModel, EntityModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Only entity types, enumeration types or primitive types are supported in this context.
And If remove ChildCategories=null
then It will give error
Internal exception has occured: The type 'EntityModel.JobCategoryModel' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.
Upvotes: 0
Views: 889
Reputation: 205799
The second case (removing the ChildCategories=null
assignment) sounds like a weird EF rule, I can't think of any logical reason for putting that constraint.
Anyway, the trick (workaround) is to define a fake derived class and project the inner select to it (with ChildCategories=null
removed). So the following works:
class JobSubCategoryModel : JobCategoryModel { }
// ...
ChildCategories = x.SubCategory.Select(y => new JobSubCategoryModel
{
CategoryName = y.CategoryName,
Identifier = y.Identifier,
ImagePath = y.Images != null ? imagePath + "/" + y.Images.ImagePath : null,
})
Upvotes: 0