I am using linq to Entity to retrieve data from to different tables by joining them, but I also want to group them by the field problemDesc in order to get rid of unnecessary duplicate entries for the same problem.
here is the code:
using (AssistantEntities context = new AssistantEntities())
{
var problems = context.tblProblems;
var customers = context.tblCustomers;
var query =
from problem in problems
join customer in customers
on problem.CustID equals customer.custID
where problem.IsActive == true
orderby customer.isMonthlyService == true descending
select new
{
problemID = problem.problemID,
ProblemCreateDate = problem.ProblemCreateDate,
CustID = problem.CustID,
name = customer.name,
isMonthlyService = customer.isMonthlyService,
StationName = problem.StationName,
problemDesc = problem.problemDesc,
LogMeIn = problem.LogMeIn
};
return query.ToList();
}
I am doing query.toList() in order to use that list in a gridview as a dataSource.
and if it possible, also add a field that count the duplicate problems.
You have plenty of examples in the following link.
LINQ - Grouping Operators
Related
I am trying to fetch all the data from my dynamodb table but unable to get as all the methods for Query / Scan operates with input parameter. so i tried getting all the rows which having primary key greater than 0.
var table = Table.LoadTable(client,Utilities.Utility.EmployeeTable);
ScanFilter filter = new ScanFilter();
filter.AddCondition("iemp_id", ScanOperator.GreaterThan, 0);
ScanOperationConfig config = new ScanOperationConfig()
{
Filter = filter,
// Optional parameters.
Select = SelectValues.SpecificAttributes,
AttributesToGet = new List<string> { "iemp_id", "demp_salary", "semp_name" }
//ConsistentRead = true
};
Search search = table.Scan(config);`
Here i am getting search.Matches = 0 where it should return data from my table.
You have only two options
1.Query : You need to supply Partition Key(mandatory) and optionally Range key.
2.Scan: Full scan of the table with out Partition key/Range Key.
In your case you will have to do full scan of the table.
DynamoDBQScanExpression scanExpression = new DynamoDBScanExpression();
scanExpression .withFilterExpression(filterexpression)
.withExpressionAttributeValues(expression values);
I am trying to work out the best method for querying all the values down a column. Should I set it as a GSI (it is currently). is it possible with a query or would I need to to do a scan?
Thanks for your help
You have to do a scan if you are not filtering by key. Here is the sample code to scan the index and get all the values.
List<String> categoryList = new ArrayList<>();
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
Table table = dynamoDB.getTable("Music");
Index index = table.getIndex("Secondary Index Name");
ItemCollection<ScanOutcome> items = null;
ScanSpec scanSpec = new ScanSpec().withSelect(Select.SPECIFIC_ATTRIBUTES).withAttributesToGet("Category");
items = index.scan(scanSpec);
Iterator<Item> pageIterator = items.iterator();
while (pageIterator.hasNext() ) {
categoryList.add(pageIterator.next().getString("Category"));
}
I got about 5 look-a-like linq querys just like this SortPerson() metod. I'm trying to develop a search using dropdowns where a user can select values from the dropdown and returns the values that are true from one or more dropdowns the user has selected to use.
Is there a simpler way to develop this? help would be much appreciated
public void SortPerson()
{
var personId = ddlPerson.SelectedValue;
var data = new MyModelContext();
var documents = from d in data.tblDocuments
join sp in data.tblPersons on d.DocPerson equals sp.PersonId
select d;
if (!String.IsNullOrEmpty(personId))
{
documents = documents.Where(c => c.DocPerson.Equals(personId));
}
rptResult.DataSource = documents.ToList();
rptResult.DataBind();
}
I don't see the point in joining without Where if you still select only one table.
If you want all document in case when Person is not selected, then you can't create much simpler method. You can write it shorter like:
var documents =
from d in data.tblDocuments
join ...
where String.IsNullOrEmpty(personId) || d.DocPerson equals personId
select d;
so you don't need separate if statement.
If you want to use several values from 5 dropdowns and use them as conditions in single query, just add more conditions:
var personId = ddlPerson.SelectedValue;
var someValue = ddlSomeDDL.SelectedValue;
//3 more values from DDL
var documents = from d in data.tblDocuments
join sp in data.tblPersons on d.DocPerson equals sp.PersonId
where (String.IsNullOrEmpty(personId) || sp.PersonId equals personId)
&& (String.IsNullOrEmpty(someValue) || d.SomeColumn equals someValue)
//3 more conditions
select d;
I have researched on the net and most result are converting from sql to linq and seldom have linq to sql.
this is the code which I want to convert to SQL :
using (CommerceEntities db = new CommerceEntities())
{
try
{
var query = (from ProductOrders in db.OrderDetails
join SelectedProducts in db.Products on ProductOrders.ProductID
equals SelectedProducts.ProductID
group ProductOrders by new
{
ProductId = SelectedProducts.ProductID,
ModelName = SelectedProducts.ModelName
} into grp
select new
{
ModelName = grp.Key.ModelName,
ProductId = grp.Key.ProductId,
Quantity = grp.Sum(o => o.Quantity)
} into orderdgrp where orderdgrp.Quantity > 0
orderby orderdgrp.Quantity descending select orderdgrp).Take(5);
RepeaterItemsList.DataSource = query;
RepeaterItemsList.DataBind();
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Load Popular Items - " +
exp.Message.ToString(), exp);
}
}
You can attempt to run the LINQ statement in LinqPad. For examples on how to use LinqPad, check the answer here.
It has a tab to show the generated SQL statement.
Here's an article on logging in LINQ to SQL. It lets you specify a TextWriter to which to send the query.
Basically, you can write something like this:
db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
... where db is your data context.
In SQL you'd write something like this (although the produced code will look a lot different, since it is auto-generated):
SELECT TOP 5 Products.ModelName, Products.ProductID, SUM(OrderDetails.Quantity) qty
FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
GROUP BY Products.ProductID, Products.ModelName
HAVING qty > 0
ORDER BY qty DESC
I have a table called Quiz that have these fields
id As Int
created As DateTime
header As Sring
body As String
fk_parent As int
url As String
All the items without parent key would be the question, and ones that have the parent key would be the answer. I am having the problem to get all the latest active questions (based both on questions created time and and answer created time).
I am struggling to write a Linq query that can do the above task.
Here's a start:
IQueryable<int> keys =
from x in dc.Quiz
let masterID = ParentId.HasValue ? ParentId.Value : Id
group x by masterID into g
order g by g.Max(x => x.created) descending
select g.Key
List<Quiz> = dc.Quiz.Where(x => keys.Take(20).Contains(x.Id)).ToList();
This assumes answers aren't parents of answers... If they can - you have an arbitrary depth tree walk on your hands, which is a wrong shaped nail for Linq and for SQL.
You could try joining the table on itself in LINQ and creating a new object that holds the Questions and answers:
var QandA = from q in tbl
join a in tbl on q.id equals a.fk_parent
select new {
QHeader = q.header,
QBody = q.body,
QUrl = q.url,
AHeader = a.header,
ABody = a.body,
AUrl = a.url
};
I think this is how your table is setup, but I might have the join wrong.