select single or multiple records using a single linq query - asp.net

I want to pass a valid id or -1("ALL") from a drop down to the function.
Can I select 'All' rows or one row based on the selected option from ddl from a table using a single linq query?

You can add an OR to the statement to get the result. Basically, (#value = -1) OR (id = #value). Whenever value is -1, it will return all value, otherwise that we be false and only return the matching record.

Having an OR in the LINQ can sometimes result in full-table scans and non-optimal retrievals.
Instead of having a condition inside your LINQ statement, I'd recommend building your LINQ query conditionally based on whether you want a single result or "all":
// Initialize your select
var query = db.Select(r => r);
// Conditionally add the "where"
if (selectedValue != -1)
query = query.Where(n => n.id == selectedValue);
// Collect your results
foreach (var record in query)
{
// ...
}
If you want all records, then your query won't include a where clause at all, otherwise, the where clause will include only the filter by id.

Related

DynamoDB Querying using Global Secondary Index

I'm trying to query all the rows which are created the last one week. I have created an index for created key in AWS console. In my query, I added the Key Condition with ComparisonOperator.GT for the created key. But When I run the query it throws an error like Query key condition not supported. If I give the condition as ComparisonOperator.EQ, it will return a single row. But not working for the ComparisonOperator.GT.
Code :
Condition rangeKeyCondition = new Condition();
rangeKeyCondition.withComparisonOperator(ComparisonOperator.GT).withAttributeValueList(new AttributeValue().withS("11:26 23/10/2018 "));
Map<String, Condition> keyConditions = new HashMap<String, Condition>();
keyConditions.put("created", rangeKeyCondition);
QueryRequest queryRequest = new QueryRequest();
queryRequest.withTableName(getTableName(TABLE_NAME));
queryRequest.withIndexName("created-index");
queryRequest.withKeyConditions(keyConditions);
QueryResult result = EventStoreInitializer.getAmazonDynamoDBClient().query(queryRequest);
I have read your case so for your desired output you should not create 'created' as Index bz it becomes key for the table and in keyCondition you can't use GT and LT operator.
you need to use FilterExpression and there you can use GT and LT for the 'created' field.

Modify query string on a form to add filter based on other fields

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.

Update multiple records in same table

I want to update multiple SalesQuotationLines the match Quotation Id X.
salesQuotationLine = salesQuotationLine::find(quotationId,true);
salesQuotationLine.selectForUpdate(true);
if(salesQuotationLine) {
ttsBegin;
SalesQuotationLine.Field = newFieldValue;
salesQuotationLine.update();
ttscommit;
The problem is, this is only updating the first record that is found within the find method.
How can I make sure, all records that match the QuotationID are being updated?
you can use this code:
while select forupdate salesQuotationLine
where salesQuotationLine.quotationId == quotationId
{
salesQuotationLine..Field = newFieldValue;
ttsbegin;
salesQuotationLine.update();
ttscommit;
}
Or can Use _update_recordset_
ttsbegin;
update_recordset salesQuotationLine
setting
Field = newFieldValue
where salesQuotationLine.quotationId == quotationId
ttscommit;
I hope to understock the question.
Dynanics AX 2012 provides way to use X++ SQL statements to enhance performance. This option is update_recordset which enables you to update multiple rows in a single trip to the server:
update_recordset salesQuotationLine
setting
Field = newFieldValue
where salesQuotationLine.quotationId == quotationId;

Perform method action based on duplicate values

I have a table, which i am creating a method on, i want run on action based on duplicatie values from 2 fields.
For example:
I have Table A which contains these fields:
IncidentDescription
Identifier
Now i want to run a certain action in the method based on the following criteria:
If the IncidentDescription already exists in another row in the same table, but only if the Identifier is different. (So it doesn't run the action if only 1 line with the IncidentDescription exists)
How can i solve this? Is it possible to accomplish this in an if statement?
Or is there a possibility/is it better to run a "while select" query, and (if it exists) run a count method based on the count result (>1).
EDIT:
I am trying to create the query as following:
select count (IncidentDescription) from TableA;
{
// I am trying to convert the result, because it gives me the error: "Operand types are not compatible with the operator, i am not sure how to make this.
serialCount = str2num(IncidentDescription);
if (IncidentDescription > 1)
//Action to go here;
}
I will build in the Identifier later.
Please use the following code as a hint and modify it according to your requirements:
TableA tableA;
TableA tableAJoin;
;
select firstOnly tableA
join tableAJoin
where tableA.IncidentDescription == tableAJoin.IncidentDescription
&& tableA.Identifier != tableAJoin.Identifier;
if (tableA.RecId)
{
info(strFmt("%1 - %2", tableA.Identifier, tableA.IncidentDescription));
info(strFmt("%1 - %2", tableAJoin.Identifier, tableAJoin.IncidentDescription));
}
If you need this check for displayOption method on a form datasource (where tableA is a datasource name), then modify it as follows
public void displayOption(Common _record, FormRowDisplayOption _options)
{
TableA tableACurrent;
TableA tableALocal;
;
tableACurrent = _record;
select firstOnly RecId from tableALocal
where tableALocal.IncidentDescription == tableACurrent.IncidentDescription
&& tableALocal.Identifier != tableACurrent.Identifier;
if (tableALocal.Identifier)
{
//record has dublicates
...
}
super(_record, _options);
}

selecting only max clause without group by properties in subquery using Nhibernate

I have SQL query like this:
select * from dbo.table1 where Id in
(
select max(id) as id from dbo.table1 group by prop1, prop2, prop3
)
I want to create NHibernate query which is be able to do this for me. I tried to use QueryOver but it doesn't work. Do you have any suggestions how to do it?
NHibernate supports even this kind of queries. Please, see more in documentation: 15.8. Detached queries and subqueries. We just have to split the query (as in your SQL snippet) into two parts:
inner select
the select with the IN clause
Let's assume, that the dbo.table1 in the Questin is mapped into MyEntity.
To create inner select, let's use the DetachedCriteria
EDIT (extended with the Group by, SqlGroupProjection)
There is an extract of the SqlGroupProjection method:
A grouping SQL projection, specifying both select clause and group by
clause fragments
// inner select
DetachedCriteria innerSelect = DetachedCriteria
.For(typeof(MyEntity))
.SetProjection(
Projections.ProjectionList()
.Add(
Projections.SqlGroupProjection(
" MAX(ID) ", // SELECT ... max(ID) only
" Prop1, Prop2, Prop3", // GROUP BY ... property1, p2...
new string[] {"ID"}, // could be empty, while not used for
new IType[] { NHibernate.NHibernateUtil.Int32 } // transformation
)
)
;
Note: I've provided even the last two paramters, but in this case they could be empty: new string[], new IType[] {}. These are used only for Transformation (materialization from data into entity). And this is not the case, we are just building inner select...
// the select with IN clause
var result = session.CreateCriteria(typeof(MyEntity))
.Add(Subqueries.PropertyIn("ID", innerSelect))
.List<MyEntity>();
Also related could be 15.7. Projections, aggregation and grouping

Resources