I have a datatable I then want to query the table and filter the data dependant numerous times. I have the following
DataTable results = new DataTable();
//fill dt from sql query
var linqResult = from myRow in results.AsEnumerable()
select myRow;
if (!string.IsNullOrEmpty(txtFilterName.Text))
{
linqResult = linqResult.Where(r => linqResult.name.ToLower.Contains(txtFilterName.Text.ToLower()));
}
I keep getting the error
'EnumerableRowCollection<DataRow>' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'EnumerableRowCollection<DataRow>'
Where name refers to the field name in the datatable
Can anyone tell me what I am doing wrong
The error message is self-explanatory.
linqResult is an IEnumerable<DataRow> which has no name property. If you want to select the column name you can use the Field-DataRow-extension method:
linqResult = linqResult.Where(r => r.Field<string>("name").ToLower.Contains(txtFilterName.Text.ToLower()));
Related
I have many-to-many rel between Products and Category. I use ef6 to mapping them
when I query to filter by request.categoryId I get these problems:
with var query = from product in _context.Products select product ;
-> I cannot get category of each product (product.categories==null)
With var query = from product in _context.Products select new {product, product.Categories };
->I cannot filter by categoryId, I want to use something like:
query = query.Where(p => p.Categories.ForEach(category=>category.Id == request.categoryId) );}
or
query = query.Where(p => p.Categories.Find(category=>category.Id==request.categoryId) )
-> The result : Anonymous type :'a{product,product.Categories}
how to product.Categories auto assign to List<Category> Categories in Product entity
I don't know how to describe my problem, help me!!
Use first query, but just add Include
var query =
from product in _context.Products.Include(x => x.Categories)
select product;
Since it is too verbose to use Query Comperhention in such case, you can try Method Chain syntax.
var query = _context.Products
.Include(x => x.Categories)
.AsQueryable(); // just for changing type to IQueryable
I've a multiselect in a form which return an array (method=get).
In the DB I've the relative field (varchar) with stored something like:
["apple","lemon","banana"]
How to search in the DB with query builder to check if array values returned from the form are in the DB?
$items = Item::where(.....
You can do something like this
$items = Item::whereIn('name', $array)->get();
I have been struggling trying to get this one to work and my brain is shot...hoping someone can help out.
I have a table called Company which is the main entity returned from the query. The company table is linked to a table called Category through the table CompanyCategory. The category table has 2 fields that are relevant here: Name and Meaning. These fields contain the same data on a row...ie...Name = "Marketing" and Meaning = "MARKETING". This allows me to query by Meaning, while the display name could potentially change in the future. I will always query the category table by Meaning, and then display the Name.
Since a company can contain 1 to many categories, there are times when I want to return all companies that have a set of categories....say...all companies that are tied to marketing or public relations. Here is the query that I have right now that returns all companies with only the data I want.
IQueryable<ICompanyModel> q = base.Context.Set<KD.CompanyAdventures.Data.Implementation.Company>()
.Include(x => x.Address.City.FirstAdminDivision)
.Include(x => x.CompanyBioInfoes)
.Select(x => new CompanyModel
{
CompanyId = x.CompanyId,
Name = x.Name,
BusinessPhone = x.BusinessPhone,
PrimaryEmail = x.PrimaryEmail,
WebsiteUrl = x.WebsiteUrl,
LogoUrl = x.LogoUrl,
Address = new AddressModel
{
AddressId = x.AddressId,
Address1 = x.Address.Address1,
Address2 = x.Address.Address2,
PostalCode = x.Address.PostalCode,
City = new CityModel
{
CityId = x.Address.City.CityId,
Name = x.Address.City.Name,
FirstAdminDivision = new FirstAdminDivisionModel
{
FirstAdminDivisionId = x.Address.City.FirstAdminDivision.FirstAdminDivisionId,
Name = x.Address.City.FirstAdminDivision.Name
}
}
}
});
I am passing a List<string> to the method (GetCompanies) that has this LINQ query and I need to filter the companies that are returned by that list of category meanings that are being passed in. I have been able to get this to work in a test with 2 simple lists using the following (where list 1 = all employees (my wife and kids names) and list 2 is just the names of the my kids):
IQueryable<string> adultEmployees = employees.Where(emp => !kids.Contains(emp.ToString())).AsQueryable();
But I am not able to get this to work with the company and category example as I can't figure out how to drill down to the meaning with complex objects....ie...not list of strings.
Object classes used by the LINQ query look like the following:
CompanyModel [ CompanyId, CompanyName, List<CategoryModel> ]
CategoryModel [ CategoryId, Name, Meaning ]
Any help is greatly appreciated.
Assume that meanings is a list containing "marketing" and "public relations". If I understand this correctly, you can get companies having CategoryModels's Meaning equals "marketing" or "public relations" like so :
companies.Where(c => c.CategoryModels.Any(cm => meanings.Contains(cm.Meaning)))
I was able to get the columns names by using this:
var props = typeof(FMCSA_NPR).GetProperties();
But it is also giving me the names of other tables which have a foreign relation with the specified table.
Is there a way by which I can only get the column names? What do we call column names when referring table as entity in Entity Model?
You can list the non-navigation properties of entities by accessing the conceptual model (CSpace):
var oc = ((IObjectContextAdapter)db).ObjectContext;
var cs = oc.MetadataWorkspace.GetEntityContainer(oc.DefaultContainerName,
DataSpace.CSpace);
foreach (var entitySet in cs.EntitySets)
{
var props = string.Join(",", entitySet.ElementType.Properties);
Trace.WriteLine(string.Format("{0}: {1}", entitySet.Name, props));
}
(Where db is your DbContext object).
I am trying to update a 'Name' DataColumn based on a 'ID' DataColumn in a DataTable.
The 'ID'-'Name' pairs are stored in a Dictionary, which is created using a DataTable extension method as follows:
public static Dictionary<object, object> ToDictionary(this DataTable dataTable, string keyColumn, string valueColumn)
{
Dictionary<object, object> resultDict = new Dictionary<object, object>();
if (dataTable.Columns.Contains(keyColumn) && dataTable.Columns.Contains(valueColumn))
{
foreach (DataRow dr in dataTable.Rows)
if (resultDict.ContainsKey(dr[keyColumn]) == false)
resultDict.Add(dr[keyColumn], dr[valueColumn]);
}
return resultDict;
}
I am using the following LINQ syntax to update the DataColumn:
misUserDetailsDT.AsEnumerable().ToList().ForEach(row => row.SetField("DepartmentName", deptDict[row["DepartmentID"]].ToString()));
Here 'misUserDetailsDT' is the DataTable containing a filled column 'DepartmentID' and an empty column 'DepartmentName'-which I am trying to update.
I have a seperate method which generates the Dictionary as follows:
var deptDict = departmentDT.ToDictionary("DeptID", "DeptName");
where 'departmentDT' is a DataTable containing columns 'DeptID' and 'DeptName'.
Now when I execute the Linq code it give a 'KeyNotFoundException'. I have thoroughly checked that the 'departmentDT' table as well as 'deptDict' have all the keys(departmentIDs) from the 'misUserDetailsDT' table. Actually the 'departmentDT' itself has been generated from all the distinct IDs of 'misUserDetailsDT' table.
I think there is some issue with figuring out the appropriate type of the Dictionary keys. I even tried casting it to Int16, but it didn't work out.
Please help me figure out a solution.
I have figured out the problem. The code works when dictionary values are casted to Int32. Thanks to #TimSchmelter for giving a very useful info. I will be changing the code to make use of foreach loop instead.