Im trying to make a query in asp.net models.
Im understand we can get a record by a primary key with ModelContext.Table.Find(id), and a list of all items with ModelContext.Table.ToList()...
My question is, how i can get a single item and entire list of items looking in another columns? for example name and lastname.
Something like ModelContext.Table.Find(new {name = "Stefan", lastname = "Luv"}) and ModelContext.Table.FindAll(new {"country"="usa"})
Thanks.
Use Where:
ModelContext.Table.Where(item => item.lastname == "Luv" && item.name == "stefan").ToList();
This is a specific example but you can of course set many kinds of predicates in the where expression.
If you want a single unique item, you can use Single():
ModelContext.Table.Single(item => item.lastname == "Luv" && item.name == "stefan");
Note this will throw an exception in case there is more than one row that satisfies your predicate.
Related
I have a Users table like this -
Table View
I am using the following query to retrieve rows where Faculty ID is CSE001, Designation is not student and User Role is not Marketing Coordinator -
Query view
But it's not giving me the result I need, cause the 2 rows I was expecting to have in return, has null in their UserRole column. So, it returns nothing.
Query Result
So, how can I write the query, so that it returns me the rows even if they have null in UserRole column? Can anyone help me, please? Thanks...
Check for both Designation and UserRole if they contain NULL values.
Use IS NULL or IS NOT NULL for these kind of checks. This is because you cannot compare NULL with specific values.
SELECT * FROM Users
WHERE FacultyId = 'CSE001'
AND (Designation <> 'Student' OR Designation IS NULL)
AND (UserRole <> 'Marketing Coordinator' OR UserRole IS NULL)
Hope this helps.
In SQL Server, values can be missing but applicable, such as the value of a hair's color that has not been supplied for a person, or can be missing but inapplicable, such as the value for a bold person. In either case, SQL Server will mark missing values as NULL. A NULL is neither TRUE, nor FALSE, but UNKNOWN. This is the third value in three-valued logic. In other words, you can determine whether X = Y is TRUE or FALSE when you know the values of both X and Y, but what if X is missing? SQL Server will return UNKNOWN, marked as NULL. This is your case: you know that Y is known (equals 'Marketing Coordinator'), but X might be missing. Because WHERE returns only those rows which match the conditions (i.e. each predicate is evaluated as TRUE), UNKNOWN results will be filtered out.
You will need to write queries that use three-valued logic to account for three possible outcomes: TRUE, FALSE and UNKNOWN. In ON, WHERE and the HEAVING clauses, SQL Server will treat NULL as FALSE. On the other hand, ORDER BY sorts the NULLs together and first.
You can test for NULL values with IS NULL or IS NOT NULL operators rather than equal.
You have explicitly ask for NULL values because they're quite special in relational databases.
This would be right one:
SELECT *
FROM Users
WHERE FacultyId <>'CSE001'
AND Designation <> 'Student'
AND (UserRole <> 'Marketing Coordinator' OR UserRole IS NULL);
I have an enquiry form which works from a view with a custom query. The form has filters, which I use in the executeQuery method of the view on the form to add ranges on various fields.
A new requirement is to filter based on two fields in the query.
Example: The PurchLine table is one of the tables in the query.
A new range is needed :
if PurchLine.ItemId != “” then
filter by PurchLine.PurchStatus == None
but, if the Item has a SPECIFIC value,
then filter by PurchStatus == Received.
(Ok, this is just an example!).
I am unable to modify my query to add a range on the PurchStatus based on the Item field.
I know exactly how the string value of the query must look, but how can I modify the query string?
The current query string looks like this (if I breakpoint on super in executeQuery):
SELECT FIRSTFAST * FROM OpenPOLinesView(OpenPOLinesView) WHERE ((CreatedDateTime<='2016-11-30T23:59:59')) AND ((VendAccount = N'S000001048'))
I want to add this at the end:
AND (((ItemId = N'') AND (PurchStatus = 0)) OR ((ItemId = N'XXX123') AND (PurchStatus = 2)))
How can I modify the query string in code?
You can use query expression for this, e.g.
queryBuildRange.value(strFmt('((%1 == %2) || ((%1 == %3) && (%4 == "%5")))',
fieldStr(InventTable, ItemType),
any2int(ItemType::Service),
any2int(ItemType::Item),
fieldStr(InventTable, ProjCategoryId),
queryValue("Spares")));
Please refer to this link Using Expressions in Query Ranges [AX 2012] for details.
I have a collection and I need to extract a name and id from each node and return them together to avoid post processing. I am trying:
extract(c IN nodes(c)| c.name +\': \'+ c.id) as results
The problem is that when a node without a name value is encountered it doesn't return anything.
Is there a way like 'and/or' to make the c.name optional allowing it to still return the c.id and a NULL for c.name?
Thanks
I would have thought at first that you could use toString to turn nulls into an empty string, but that doesn't seem to work. coalesce should help, though:
extract(c IN nodes(c)| coalesce(c.name, '') +\': \'+ c.id) as results
I have been trying to solve this problem and I can't seem to figure it out. I'm not sure if it's because of my db design and LINQ, but I'm hoping for some direction here.
My db table:
Id Name ParentId
1 Data1 null
2 Data2 null
3 Data3 null
4 Data4 1
5 Data5 1
6 Data6 2
7 Data7 2
Basically Data1 and Data2 are the top levels that I want to use for headings and their children will be related based on their ParentID.
I am trying to use a listview to present the data like the following:
Data1
-----
Data4
Data5
Data2
-----
Data6
Data7
I am trying to use a combination of LINQ and listview to accomplish this.
The following is the code for the linq query:
var query = from data in mydb.datatable
where data.ParentId == null
select data;
But this only gives the heading level... and unfortunately listview only takes in 1 datasource.
While it's possible with some databases (like SQL Server post 2005) to write recursive queries, I don't believe those get generated by LINQ. On the other hand, if the number of records is sufficiently small, you could materialize the data (to a list) and write a LINQ query that uses a recursive function to generate your list.
This is from memory, but it would look something like this:
Func<int?,IEnumerable<data>> f = null;
f = parentId => {
IEnumerable<data> result = from data in mydb.datatable
where data.ParentId = parentId
select data;
return result.ToList().SelectMany(d=>f(d.Id));
};
That should get you the hierarchy.
If your hierarchy has only two levels you can use a group join and anonymous objects:
var query = from data in mydb.datatable.Where(x => x.ParentId == null)
join child in mydb.datatable.Where(x => x.ParentId != null)
on data.Id equals child.ParentId into children
select new { data, children };
Edit: You will have to convert the data to a collection that can be bound to a ListView. One hack would be to have a list that is only one level deep with spacing in front of the subitems:
var listViewItems = (from item in query.AsEnumerable()
let dataName = item.data.Name
let childNames = item.children.Select(c => " " + c.Name)
from name in dataName.Concat(childNames)
select new ListViewItem(name)).ToArray();
You could also try to find a control that fits better, like a TreeView. You might want to ask a separate question about this issue.
I just wrote up a blog post describing a solution to build a graph from a self-referencing table with a single LINQ query to the database which might be of use. See http://www.thinqlinq.com/Post.aspx/Title/Hierarchical-Trees-from-Flat-Tables-using-LINQ.
I need to calculate sum of InvnetTrans'es that have specific physicial dimensions[inventTransPosting.Dimension] on specific date. I.e. I need analogue of
select sum(CostAmountPosted) //other sums
from InventTrans
where InventTrans.transDate < 3\3\2010
exists join InventTransPosted
where InventTransPosted.dimension[1] == 'XXX'
&& InventTransPosted.inventTransId == inventTrans.inventTransId
&& //other relations
It is possible to calculate InvenTrans sum with InventSum* classes filtering InvenTranses by InventDim.
Is it possible somehow to filter by non inventdim dimensions?
Or it is neccessary to change InventSum* classes?
Right now I don't see that inventSum* classes can filter by Dimensions. Maybe I missed some classes?
Restructure your select:
select sum(CostAmountPosted) //other sums
from InventTrans
exists join InventTransPosting
where InventTransPosting.dimension[1] == 'XXX'
&& InventTransPosting.transDate < 3\3\2010
&& InventTransPosting.inventTransId == inventTrans.inventTransId
&& InventTransPosting.itemId == inventTrans.itemId
&& //other relations
Make relevant index on InventTransPosting with Dimension[1] as first index field and TransDate as second.
Take a look on the InventOnHand class.
It sums the invent on-hand values based on criteria like item id and inventory dimensions (but not financial dimensions).
There are several constructor methods to InventOnhand name new like newInventBatch.
You could store - redundantly - amountPosted on InventTransPosted table, then make a relevant index.
The filling of the amountPosted on existing transaction may be problematic.
Is it worth it?
Or could you use a BI tool to do your report?