Linq Implementation With Dynamic GroupBy Clause - linq

In the bellow Linq Statement, i am facing an error in "Select" while trying to fetch, datatable field like "ID" and assign it to row["ID"].
//row["ID"] = g.Field<decimal>("ID");
Error Message:
System.Linq.IGrouping<string,System.Data.DataRow> does not contain a definition for 'Field'
var x = groupedDataRow
.AsEnumerable()
.Select(g =>
{
var row = dataTable.NewRow();
//row["ID"] = g.Field<decimal>("ID");
row["AMT"] = g.Sum(r => r.Field<decimal>("AMT"));
row["PERCENTAGE"] = g.Sum(r => r.Field<decimal>("PERCENTAGE"));
return row;
}).CopyToDataTable();
How retrieve datatable field like "ID" so that it could be assigned to row["ID"] in the Select statement?
Linq Example
public class Program
{
static StringBuilder stringBuilder = new StringBuilder();
public static String GroupData(DataRow dataRow)
{
String[] columnNames = new[] {"ID","COL1", "COL2"};
stringBuilder.Remove(0, stringBuilder.Length);
foreach (String column in columnNames)
{
stringBuilder.Append(dataRow[column].ToString());
}
return stringBuilder.ToString();
}
public static void Main()
{
DataTable dataTable = new DataTable("MyTable");
DataColumn dc2 = dataTable.Columns.Add("ID", typeof(decimal));
dataTable.Columns.Add("AMT", typeof(decimal));
dataTable.Columns.Add("PERCENTAGE", typeof(decimal));
dataTable.Columns.Add("COL1", typeof(String));
dataTable.Columns.Add("COL2", typeof(String));
dataTable.Rows.Add(000, 400,100,"sss","vvv");
dataTable.Rows.Add(888, 400, 100,"qqq","fff");
dataTable.Rows.Add(000, 300, 100,"eee","aaa");
dataTable.Rows.Add(000, 300, 100,"eee","aaa");
dataTable.Rows.Add(000,400,100,"sss","vvv");
EnumerableDataRowList<DataRow> enumerableRowCollection = new EnumerableDataRowList<DataRow>(dataTable.Rows);
Func<DataRow, String> groupingFunction = GroupData;
var groupedDataRow = enumerableRowCollection.GroupBy(groupingFunction);
var x = groupedDataRow.AsEnumerable()
.Select(g =>
{
var row = dataTable.NewRow();
//row["ID"] = g.Field<decimal>("ID");
row["AMT"] = g.Sum(r => r.Field<decimal>("AMT"));
row["PERCENTAGE"] = g.Sum(r => r.Field<decimal>("PERCENTAGE"));
return row;
}).CopyToDataTable();
foreach(DataRow row in x.Rows)
{
Console.WriteLine(row["ID"].ToString() + " " + row["COL1"].ToString() + " " + row["COL2"].ToString() + " " + row["AMT"].ToString() + " " + row["PERCENTAGE"].ToString()) ;
}
}
class EnumerableDataRowList<T> : IEnumerable<T>, IEnumerable
{
IEnumerable dataRows;
internal EnumerableDataRowList(IEnumerable items)
{
dataRows = items;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
foreach (T dataRow in dataRows)
yield return dataRow;
}
IEnumerator IEnumerable.GetEnumerator()
{
IEnumerable<T> iEnumerable = this;
return iEnumerable.GetEnumerator();
}
}

It's because g is an IGrouping which doesn't have a Field member.
You could maybe try something like:
var x = groupedDataRow.AsEnumerable()
.Select(g =>
{
var row = dataTable.NewRow();
row["ID"] = g.Select(r => r.Field<decimal>("ID")).FirstOrDefault();
row["AMT"] = g.Sum(r => r.Field<decimal>("AMT"));
row["PERCENTAGE"] = g.Sum(r => r.Field<decimal>("PERCENTAGE"));
return row;
}).CopyToDataTable();
or
var x = groupedDataRow.AsEnumerable()
.Select(g =>
{
var row = dataTable.NewRow();
row["ID"] = g.First().Field<decimal>("ID");
row["AMT"] = g.Sum(r => r.Field<decimal>("AMT"));
row["PERCENTAGE"] = g.Sum(r => r.Field<decimal>("PERCENTAGE"));
return row;
}).CopyToDataTable();
It should be safe to use g.First() because a group is only a group if it contains any items.

Related

LinqToDB Exception cannot be converted to SQL

Hello I have an issue with this query
var queryGrouped = queryFiltered
.GroupBy(c => new { c.Id, c.TableOneId, c.TableOneName, c.TableTwoId, c.TableTwoName, c.TableTwoCode, c.TableThreeId, c.TableThreeName, c.Description, c.EffectiveDate, c.CreatedBy, c.ServiceGroupName })
.DisableGuard()
.Select(cg => new Model
{
Id = cg.Key.Id,
TableOneId = cg.Key.TableOneId,
TableOneName = cg.Key.TableOneName,
TableTwoId = cg.Key.TableTwoId,
TableTwoCode = cg.Key.TableTwoCode,
TableTwoName = cg.Key.TableTwoName,
TableThreeId = cg.Key.TableThreeId,
TableThreeName = cg.Key.TableThreeName,
Description = cg.Key.Description,
EffectiveDate = cg.Key.EffectiveDate,
EffectiveDateText = cg.Key.EffectiveDate != null ? cg.Key.EffectiveDate.Value.ToString("MM/dd/yyyy") : string.Empty,
ServiceGroupName = string.Join(", ", cg.Select(g => g.ServiceGroupName).Distinct()),
CreatedBy = cg.Key.CreatedBy
}).OrderBy(x => x.ServiceGroupName).ToListAsync();
If i run this when try to order by the field ServiceGroup it returns this message
LinqToDB.Linq.LinqException: ''Join(", ", cg.Select(g => g.ServiceGroupName).Distinct())' cannot be converted to SQL.'
So I don't know how to order by this field ServiceGroupName, thanks for any answer.
I would suggest to make grouping on the client side. Note that I have removed ServiceGroupName from grouping key.
var data = await queryFiltered
.Select(c => new {
c.Id,
c.TableOneId,
c.TableOneName,
c.TableTwoId,
c.TableTwoName,
c.TableTwoCode,
c.TableThreeId,
c.TableThreeName,
c.Description,
c.EffectiveDate,
c.CreatedBy,
c.ServiceGroupName
})
.ToListAsync();
var queryGrouped = data
.GroupBy(c => new { c.Id, c.TableOneId, c.TableOneName, c.TableTwoId, c.TableTwoName, c.TableTwoCode, c.TableThreeId, c.TableThreeName, c.Description, c.EffectiveDate, c.CreatedBy })
.Select(cg => new Model
{
Id = cg.Key.Id,
TableOneId = cg.Key.TableOneId,
TableOneName = cg.Key.TableOneName,
TableTwoId = cg.Key.TableTwoId,
TableTwoCode = cg.Key.TableTwoCode,
TableTwoName = cg.Key.TableTwoName,
TableThreeId = cg.Key.TableThreeId,
TableThreeName = cg.Key.TableThreeName,
Description = cg.Key.Description,
EffectiveDate = cg.Key.EffectiveDate,
EffectiveDateText = cg.Key.EffectiveDate != null ? cg.Key.EffectiveDate.Value.ToString("MM/dd/yyyy") : string.Empty,
ServiceGroupName = string.Join(", ", cg.Select(g => g.ServiceGroupName).Distinct()),
CreatedBy = cg.Key.CreatedBy
})
.OrderBy(x => x.ServiceGroupName)
.ToList();

asp.net core3 error: not all code paths return a value

I have two tables with similar data for body insurance and third party car insurance ... I have used enum in the model to separate the insurances and I want to do the creation operation for it .... There are two modes for each insurance. One case when that car does not have insurance yet and the second case when we want to extend it.
I wrote this code to create the form, but it encounters the following error
I also get an error on the name of the Create function.error = not all code paths return a value.
Please advise
public async Task<IActionResult> Create(int id, int type)
{
InsuranceViewModel model;
ViewBag.Type = type;
var companies = await _context.InsuranceCompany
.Where(e => e.IsActice)
.ToListAsync();
ViewData["CompanyList"] = new SelectList(companies, "Id", "CompanyName");
if ((InsuranceType)type == InsuranceType.Body)
{
var bodyInsurance = await _context.BodyInsurance
.Include(e => e.InsuranceCompany)
.FirstOrDefaultAsync(e => e.Id == id);
if (bodyInsurance == null)
{
model = new InsuranceViewModel
{
CompanyId = bodyInsurance.InsuranceCompanyId,
CompanyName = bodyInsurance.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(bodyInsurance.IssueDate).Ticks,
ExpireDate = new DateTime(bodyInsurance.ExpireDate).Ticks,
VehicleInformationId = id
};
}
else
{
var lastBody = await _context.BodyInsurance.Include(e => e.InsuranceCompany)
.Where(e => e.VehicleInformationId == id)
.OrderBy(e => e.ExpireDate)
.LastAsync();
model = new InsuranceViewModel
{
ExpireDate = new DateTime(lastBody.ExpireDate).AddYears(1).AddDays(1).Ticks,
CompanyId = lastBody.InsuranceCompanyId,
CompanyName = lastBody.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(lastBody.ExpireDate).AddDays(1).Ticks,
VehicleInformationId = id
};
}
}
else
{
if ((InsuranceType)type == InsuranceType.Thirdpart)
{
var thirdParty = await _context.ThirdPartyInsurance
.Include(e => e.InsuranceCompany)
.FirstOrDefaultAsync(e => e.Id == id);
if (thirdParty == null)
{
model = new InsuranceViewModel
{
CompanyId = thirdParty.InsuranceCompanyId,
CompanyName = thirdParty.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(thirdParty.IssueDate).Ticks,
ExpireDate = new DateTime(thirdParty.ExpireDate).Ticks,
VehicleInformationId = id
};
}
else
{
var lastThirdParty = await _context.ThirdPartyInsurance.Include(e => e.InsuranceCompany)
.Where(e => e.VehicleInformationId == id)
.OrderBy(e => e.ExpireDate)
.LastAsync();
model = new InsuranceViewModel
{
ExpireDate = new DateTime(lastThirdParty.ExpireDate).AddYears(1).AddDays(1).Ticks,
CompanyId = lastThirdParty.InsuranceCompanyId,
CompanyName = lastThirdParty.InsuranceCompany.CompanyName,
InsuranceType = InsuranceType.Body,
IssueDate = new DateTime(lastThirdParty.ExpireDate).AddDays(1).Ticks,
VehicleInformationId = id
};
}
}
return View(model);
}

Dynamic where clause with two entity

I need a filter between two entity.
Have two tables 1.User 2.Product
Product map with the User table.
I am going to create a dynamic where filter.
I need to find out all the users which have 'test' product.
Conditions: if userFilter count is 0 then I need all test product with the respected user.
If userFilter is there and productFilter is there then below code is working but if userFilter is not there and productFilter is there then it returning 0 row. How can I find the users which have test product? ?
Here is my Code.
public IHttpActionResult GetFilter()
{
var userFilters = new List<Filter>()
{
new Filter { PropertyName = "Username" ,
Operation = Op .Equals, Value = "Karan" },
};
var productfilter = new List<Filter>()
{
new Filter { PropertyName = "Name" ,
Operation = Op .Equals, Value = "Test product" }
};
Func<User, bool> deleg = x => true;
Func<Product, bool> delegProduct = x => true;
if (userFilters.Count > 0)
{
deleg = ExpressionBuilder.GetExpression<User>(userFilters).Compile();
}
if (productfilter.Count > 0)
{
delegProduct = ExpressionBuilder.GetExpression<Product>(productfilter).Compile();
}
var resultt = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
return Ok(resultt);
}
if i understand correct, you need all users that have test product when userFiler count is 0.
List<User> res;
var user = _localmarketEntities.Users.Where(deleg).ToList();
if (user.Count == 0) {
res = _localmarketEntities.Products.Where(delegProduct).Select(q => new User() {
Id = q.Id,
Username = q.Username,
Product = q
}).ToList();
}
else {
res = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
}

Convert Lambda Expression into an Expression tree

I have that lambda:
var Ids = profileExample.CostCenters
.Where(CostCentre => CostCentre != null)
.Select(CostCentre => CostCentre.Id);
Then i convert to that expression tree
static IEnumerable<Int64> AboveLambdaConvertedToExpressionTree(Profile profileExample)
{
//Begin var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
var property = profileExample.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name != "Id").First();
var collection = ((IEnumerable)property.GetValue(profileExample, null)).AsQueryable();
var collectionType = property.PropertyType.GetGenericArguments()[0];
var collectionTypeName = collectionType.Name;
var keyType = typeof(Int64);
var keyName = "Id";
//BeginWhere
var parameter = Expression.Parameter(collectionType, collectionTypeName);
var profileExampleWhere = Expression.Lambda(
Expression.NotEqual(parameter, Expression.Constant(null)),
parameter);
var profileExampleWhereCall = Expression.Call(typeof(Enumerable),
"Where",
new Type[] { collectionType },
collection.Expression,
profileExampleWhere);
//EndWhere
//BeginSelect
var profileExampleSelect = Expression.Lambda(Expression.PropertyOrField(parameter, keyName),
parameter);
var profileExampleSelectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { collectionType, keyType },
profileExampleWhereCall,
profileExampleSelect);
var Ids = Expression.Lambda(profileExampleSelectCall).Compile().DynamicInvoke();
//EndSelect
//End var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
return ((IEnumerable)Ids).Cast<Int64>();
}
Now i want to do the same with bellow lambda
var result = Set.AsQueryable()
.Where(Profile => Profile.CostCenters.Select(CostCentre => CostCentre.Id)
.Any(Id => Ids.Contains(Id))).ToList();
But i stuck in .Any(Id => Ids.Contains(Id))....
var id = Expression.Parameter(typeof(long), "Id");
var costCentre = Expression.Parameter(typeof(CostCentre), "CostCentre");
var profile = Expression.Parameter(typeof(Profile), "Profile");
var selectLambda = Expression.Lambda(Expression.PropertyOrField(costCentre, "Id"), costCentre);
var selectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { typeof(CostCentre), typeof(long) },
Expression.PropertyOrField(profile, "CostCenters"),
selectLambda);
How can i call Any from selectCall and call Ids.Contains...
Full code to run as console application bellow:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace ExpressionTrees
{
class Program
{
static void Main(string[] args)
{
var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
Ids = AboveLambdaConvertedToExpressionTree(profileExample);
var result = Set.AsQueryable().Where(Profile => Profile.CostCenters.Select(CostCentre => CostCentre.Id).Any(Id => Ids.Contains(Id))).ToList();
//Expression<Func<Profile, bool>> lambda = (Profile) => Profile.CostCenters.Select(CostCentre => CostCentre.Id).Any(Id => Ids.Contains(Id));
var id = Expression.Parameter(typeof(long), "Id");
var costCentre = Expression.Parameter(typeof(CostCentre), "CostCentre");
var profile = Expression.Parameter(typeof(Profile), "Profile");
var selectLambda = Expression.Lambda(Expression.PropertyOrField(costCentre, "Id"), costCentre);
var selectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { typeof(CostCentre), typeof(long) },
Expression.PropertyOrField(profile, "CostCenters"),
selectLambda);
}
static IEnumerable<Int64> AboveLambdaConvertedToExpressionTree(Profile profileExample)
{
// I show that as example of what i need to do
var keyType = typeof(Int64);
var keyName = "Id";
//Begin var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
var property = profileExample.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.Name != keyName).First();
var collection = ((IEnumerable)property.GetValue(profileExample, null)).AsQueryable();
var collectionType = property.PropertyType.GetGenericArguments()[0];
var collectionTypeName = collectionType.Name;
//BeginWhere
var parameter = Expression.Parameter(collectionType, collectionTypeName);
var profileExampleWhere = Expression.Lambda(
Expression.NotEqual(parameter, Expression.Constant(null)),
parameter);
var profileExampleWhereCall = Expression.Call(typeof(Enumerable),
"Where",
new Type[] { collectionType },
collection.Expression,
profileExampleWhere);
//EndWhere
//BeginSelect
var profileExampleSelect = Expression.Lambda(Expression.PropertyOrField(parameter, keyName),
parameter);
var profileExampleSelectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { collectionType, keyType },
profileExampleWhereCall,
profileExampleSelect);
var Ids = Expression.Lambda(profileExampleSelectCall).Compile().DynamicInvoke();
//EndSelect
//End var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
return ((IEnumerable)Ids).Cast<Int64>();
}
public partial class Profile
{
public virtual Int64 Id { get; set; }
public virtual ICollection<CostCentre> CostCenters { get; set; }
}
public partial class CostCentre
{
public virtual Int64 Id { get; set; }
}
public static Profile profileExample
{
get
{
return new Profile()
{
Id = 1,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 2 } }
};
}
}
public static IList<Profile> Set
{
get
{
return new List<Profile>() { new Profile() { Id = 1,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 1 },
new CostCentre() { Id = 2 } }
},
new Profile() { Id = 2,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 2 },
new CostCentre() { Id = 3 } }
},
new Profile() { Id = 3,
CostCenters = new List<CostCentre>() { new CostCentre() { Id = 3 } }
} };
}
}
}
}
Since Any is a Generic Method you need to create it for a specific type. The method below gets the Any<T> method from the Enumerable type.
public static MethodInfo GetAnyExtensionMethod(Type forType)
{
MethodInfo method =
typeof(Enumerable).GetMethods()
.First(m => m.Name.Equals("Any") &&
m.GetParameters().Count() == 2);
return method.MakeGenericMethod(new[] { forType });
}
Its solved with help of Mads from MS
class Program
{
static void Main(string[] args)
{
//var Ids = profileExample.CostCenters.Where(CostCentre => CostCentre != null).Select(CostCentre => CostCentre.Id);
var Ids = AboveLambdaConvertedToExpressionTree(profileExample);
//var result = Set.AsQueryable().Where(Profile => Profile.CostCenters.Select(CostCentre => CostCentre.Id).Any(Id => Ids.Contains(Id))).ToList();
var id = Expression.Parameter(typeof(long), "Id");
var costCentre = Expression.Parameter(typeof(CostCentre), "CostCentre");
var profile = Expression.Parameter(typeof(Profile), "Profile");
var selectLambda = Expression.Lambda(Expression.PropertyOrField(costCentre, "Id"), costCentre);
var selectCall = Expression.Call(typeof(Enumerable),
"Select",
new Type[] { typeof(CostCentre), typeof(long) },
Expression.PropertyOrField(profile, "CostCenters"),
selectLambda);
//var id2 = Expression.Parameter(typeof(long), "Id");
var containsCall = Expression.Call(typeof(Enumerable),
"Contains",
new Type[] { typeof(long) },
Expression.Constant(Ids),
id);
var anyLambda = Expression.Lambda(containsCall, id);
var anyCall = Expression.Call(typeof(Enumerable),
"Any",
new Type[] { typeof(long) },
selectCall,
anyLambda);
var whereLambda = Expression.Lambda(anyCall, profile);
var callExpression = Expression.Call(typeof(Queryable),
"Where",
new Type[] { typeof(Profile) },
Set.AsQueryable().Expression,
whereLambda);
var result = Expression.Lambda(callExpression).Compile().DynamicInvoke();
}

how to use (dynamic)null concept to this query

i wan to bind grid view with different kinds of conditions show here i'm use (dynamic)null concept for query declaration but at end of rest i can't getting field that associated with query.
here i put my code :
public void FillGrid(string GroupByText, string ColumnName, string SearchText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = (dynamic)null;
switch (GroupByText)
{
case "Enquiry":
query = db.Enquiries.Where(i => i.enttype_id.Equals("1")).OrderByDescending(i => i.Created_date).Select(i => new
{
Ref_no = i.Ref_no,
Name = db.Parties.Where(p => p.Id.Equals(i.party_id)).Select(p => p.Name).SingleOrDefault(),
StatusName = db.Status.Where(s => s.Id.Equals(i.status_id)).Select(s => s.StatusName).SingleOrDefault(),
CategoryName = db.Categories.Where(c => c.Id.Equals(i.category_id)).Select(c => c.category_name).SingleOrDefault(),
IsUregent = i.IsUregent,
Created_date = i.Created_date
}).FilterForColumn(ColumnName,SearchText).ToList();
break;
case "Visit":
query = db.Enquiries.Where(i => i.enttype_id.Equals("2")).OrderByDescending(i => i.Created_date).Select(i => new
{
Ref_no = i.Ref_no,
Name = db.Parties.Where(p => p.Id.Equals(i.party_id)).Select(p => p.Name).SingleOrDefault(),
StatusName = db.Status.Where(s => s.Id.Equals(i.status_id)).Select(s => s.StatusName).SingleOrDefault(),
CategoryName = db.Categories.Where(c => c.Id.Equals(i.category_id)).Select(c => c.category_name).SingleOrDefault(),
IsUregent = i.IsUregent,
Created_date = i.Created_date
}).FilterForColumn(ColumnName,SearchText).ToList();
break;
default:
query = db.Enquiries.OrderByDescending(i => i.Created_date).Select(i => new
{
Ref_no = i.Ref_no,
Name = db.Parties.Where(p => p.Id.Equals(i.party_id)).Select(p => p.Name).SingleOrDefault(),
StatusName = db.Status.Where(s => s.Id.Equals(i.status_id)).Select(s => s.StatusName).SingleOrDefault(),
CategoryName = db.Categories.Where(c => c.Id.Equals(i.category_id)).Select(c => c.category_name).SingleOrDefault(),
IsUregent = i.IsUregent,
Created_date = i.Created_date
}).FilterForColumn(ColumnName, SearchText).ToList();
break;
}
int count = 0;
DataSet myDataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Ref_no", typeof(string)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("StatusName", typeof(int)));
dt.Columns.Add(new DataColumn("CategoryName", typeof(string)));
dt.Columns.Add(new DataColumn("IsUregent", typeof(bool)));
dt.Columns.Add(new DataColumn("Created_date", typeof(DateTime)));
foreach (var item in query)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Ref_no"] = item.//not founding field that
}
}
}
}
what is the return type of .FilterForColumn(ColumnName,SearchText) ?
if it does just filtering, without changing the Data Type, i think you can use this:
var query = Enumerable.Repeat(new
{
Ref_no = string.Empty,
Name = string.Empty,
StatusName = default(int),
CategoryName = string.Empty,
IsUregent = default(bool),
Created_date = default(DateTime)
}, 0)
.ToList();
instead of this:
var query = (dynamic)null;
and probably this can solve your problem

Resources