How to Sortby Multiple Colums - Linq to SQL - linq

Wanting to sortby x.IRNumber - .thenby x.BedLocation but no luck could someone help me in the right direction?
Thanks
Mark
string jobID = ddlJobID.SelectedValue;
using (rw_forms context = new rw_forms())
{
var result = from c in context.hospedia_running_sheet_view.Select(x => new
{
x.uniqueID,
x.irNumber,
x.ward,
x.bed_location,
x.bed_extension,
x.select_technology,
x.select_fitting_of_pattress,
x.select_fitting_of_backplate,
x.fixing_method_used,
x.id,
x.status,
x.latitude,
x.longitude,
x.accuracy,
x.createdAt,
x.createdByName,
x.fixing,
x.statusID,
x.commissioningID,
x.jobID,
x.siteName
}).Where(x=> x.statusID == 1).Where(x => x.jobID == ((jobID == "-1") ? x.jobID : jobID)).OrderByDescending(x => x.irNumber) select c;
grdForms.DataSource = result.ToList();
grdForms.DataBind();
}
}
catch(Exception ex)
{
Response.Write(ex.ToString());
}
}

If you want something like this
SELECT * FROM TEST
ORDER BY TEST.ID,TEST.RID DESC
-
from t in db.TEST
orderby t.ID, t.RID descending
select t

Related

Return the result of joining two tables in Silverlight 4.0

Main Code:
DomainServiceAccountManager d = new DomainServiceAccountManager();
EntityQuery<ListBuy> q = d.GetListMemberBuyQuery();
LoadOperation<ListBuy> l = d.Load(q);
DGListBuy.ItemsSource = l.Entities;
The code:
public IQueryable<ListBuy> GetListMemberBuy()
{
var membuy =
from mem in this.ObjectContext.Members
from b in this.ObjectContext.Buys.Where(b => b.ID_member == mem.ID)
.OrderByDescending(b => b.ID)
.DefaultIfEmpty()
select new { b.ID, mem.Name, b.Money, b.Tarikh };
return membuy;
}
I get the following message:
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<AccountManager.Web.ListBuy>'. An explicit conversion exists (are you missing a cast?)
You method GetListMemberBuy actually returns an IQueryable of anonymous type instead of an IQueryable of type ListBuy. These are not identical, hence the (compile time?) error.
I can only assume that ListBuy also exists in the database, but if so, then you can remove the anonymous type.
public IQueryable<ListBuy> GetListMemberBuy()
{
var membuy =
from mem in this.ObjectContext.Members
from b in this.ObjectContext.Buys.Where(b => b.ID_member == mem.ID)
.OrderByDescending(b => b.ID)
.DefaultIfEmpty()
select new ListBuy() { ID = b.ID, Name = mem.Name, Money = b.Money, Tarikh = b.Tarikh }; // <-- new ListBuy() !!
return membuy;
}
If ListBuy does not exist in the database, then you cannot return an IQueryable. Maybe this will work.
public IEnumerable<ListBuy> GetListMemberBuy()
{
var membuy =
from mem in this.ObjectContext.Members
from b in this.ObjectContext.Buys.Where(b => b.ID_member == mem.ID)
.OrderByDescending(b => b.ID)
.DefaultIfEmpty()
select new { b.ID, mem.Name, b.Money, b.Tarikh };
return membuy
.AsEnumerable()
.Select(b => new ListBuy() {
ID = b.ID, Name = b.Name, Money = b.Money, Tarikh = b.Tarikh
});
}
All this is a bit speculation since you didn't include the ListBuy class definition in your question.

Dynamically Set Column Name In LINQ Query

Im trying to write a method which will allow me to search different DataTables, over different columns.
So far i have the following:
string selectedValue;
string searchColumn;
string targetColumn;
var results = (from a in dt.AsEnumerable()
where a.Field<string>(searchColumn) == selectedValue
select new
{
targetColumn = a.Field<string>(targetColumn)
}).Distinct();
Which kind of gets the job done, but I'm left with the column name as targetColumn rather than the actual column name I want.
Is there any way to resolve this?
Thanks in advance
CM
I make a LINQ to Datatables
public List<DataRow> Where(this DataTable dt, Func<DataRow, bool> pred)
{
List<DataRow> res = new List<DataRow>();
try {
if (dt != null && dt.Rows.Count > 0) {
for (i = 0; i <= dt.Rows.Count - 1; i++) {
if (pred(dt(i))) {
res.Add(dt(i));
}
}
}
} catch (Exception ex) {
PromptMsg(ex);
}
return res;
}
Usage :
var RowsList = dt.Where(f => f("SomeField").toString() == "SomeValue" ||
f("OtherField") > 5);

Good practice for using "NOT IN" in a LINQ query

I have converted the following SQL query to LINQ with the exception of the "NOT IN" subquery.
What would be the most effective way to implement this using LINQ? Should I use a join instead?
If anybody is able to provide an example or some guidance, I'd appreciate it.
New LINQ Query:
return from objOpenCalls in db.OpenItemss
from objTasks in db.Tasks
.Where(t => (t.Task_ID == objOpenCalls.Parent_Task_ID))
where ((objTasks.Item_ID > 0) && (objTasks.Type_ID > 0) && (objTasks.OwnerTypeItem_ID == user) && (objOpenCalls.CallEnd < DateTime.Now))
orderby objOpenCalls.CallStart descending
select new CallMiniViewModel
{
ID = objOpenCalls.ID,
CallStart = objOpenCalls.CallStart,
Name = objTasks.Task_Title
};
Old SQL Query:
SELECT TOP (100) ta.ID, t.Task_Title, ta.CallStart
FROM OpenItems AS ta INNER JOIN
Tasks AS t ON ta.Parent_Task_ID = t.Task_ID
WHERE
(t.Item_ID > 0) AND (t.[Type_ID] > 0) AND (ta.CallStart > DATEADD(m, -6, GETDATE()))
AND (ta.ID NOT IN (SELECT CallId FROM CallFeedback)) AND (t.OwnerTypeItem_ID = #Username) AND (ta.CallEnd < GETDATE())
ORDER BY ta.CallStart DESC
There are a couple of ways of doing the not in. Below is just a quick sample put in LinqPad as a test.
class MyClass {
public int Id {get;set;}
}
void Main()
{
int[] myItems = new[] { 1, 2, 3, 4, 5, 6 };
IEnumerable<MyClass> classes = new []{
new MyClass { Id = 3 },
new MyClass { Id = 6 },
new MyClass { Id = 8 }
};
var results = from cl in classes
where !myItems.Contains( cl.Id )
select cl;
foreach(var result in results) {
Console.WriteLine( "Class {0}", result.Id);
}
var results2 = from cl in classes
where (
from i in myItems
where i == cl.Id
select i ).Count( ) == 0
select cl;
foreach(var result in results2) {
Console.WriteLine( "Class {0}", result.Id);
}
}
I normally play with code first in LinqPad as it helps me understand any problems, and it will (if you're working with SQL) then show you what SQL the query will generate and you can fine tune a little. Sometimes it takes a little time to get your stuff able to be run in there, but it's worth it with the more complex queries.

LINQ: Group By + Where in clause

I'm trying to implement a T-SQL equivalent of a where in (select ...) code in LINQ.
This is what I have now:
int contactID = GetContactID();
IEnumerable<string> threadList = (from s in pdc.Messages
where s.ContactID == contactID
group 1 by new { s.ThreadID } into d
select new { ThreadID = d.Key.ThreadID}).ToList<string>();
var result = from s in pdc.Messages
where threadList.Contains(s.ThreadID)
group new { s } by new { s.ThreadID } into d
let maxMsgID = d.Where(x => x.s.ContactID != contactID).Max(x => x.s.MessageID)
select new {
LastMessage = d.Where(x => x.s.MessageID == maxMsgID).SingleOrDefault().s
};
However, my code won't compile due to this error for the ToList():
cannot convert from
'System.Linq.IQueryable<AnonymousType#1>'
to
'System.Collections.Generic.IEnumerable<string>'
Anyone have any suggestions on how to implement this? Or any suggestions on how to simplify this code?
Your query returns a set of anonymous types; you cannot implicitly convert it to a List<string>.
Instead, you should select the string itself. You don't need any anonymous types.
Change it to
var threadList = pdc.Messages.Where(s => s.ContactID == contactID)
.Select(s => s.ThreadID)
.Distinct()
.ToList();
var result = from s in pdc.Messages
where threadList.Contains(s.ThreadID)
group s by s.ThreadID into d
let maxMsgID = d.Where(x => x.ContactID != contactID).Max(x => x.MessageID)
select new {
LastMessage = d.Where(x => x.MessageID == maxMsgID).SingleOrDefault()
};

Linq: Nested queries are better than joins, but what if you use 2 nested queries?

In her book Entity Framework Julie Lerman recommends using nested queries in preference to joins (scroll back a couple of pages).
In her example see populates 1 field this way, but what id you want to populate 2?
I have an example here where I would prefer to populate the Forename and Surname with the same nested query rather than 2 separate ones. I just need to know the correct syntax to do this.
public static List<RequestInfo> GetRequests(int _employeeId)
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
return db.AnnualLeaveBookeds
.Where(x => x.NextApproverId == _employeeId ||
(x.ApproverId == _employeeId && x.ApprovalDate.HasValue == false))
.Select(y => new RequestInfo
{
AnnualLeaveDate = y.AnnualLeaveDate,
Forename = (
from e in db.Employees
where e.EmployeeId == y.EmployeeId
select e.Forename).FirstOrDefault(),
Surname = (
from e in db.Employees
where e.EmployeeId == y.EmployeeId
select e.Surname).FirstOrDefault(),
RequestDate = y.RequestDate,
CancelRequestDate = y.CancelRequestDate,
ApproveFlag = false,
RejectFlag = false,
Reason = string.Empty
})
.OrderBy(x => x.AnnualLeaveDate)
.ToList();
}
}
There's nothing wrong with your query, but you can write it in a way that is much simpler, without the nested queries:
public static List<RequestInfo> GetRequests(int employeeId)
{
using (SHPContainerEntities db = new SHPContainerEntities())
{
return (
from x in db.AnnualLeaveBookeds
where x.NextApproverId == employeeId ||
(x.ApproverId == employeeId && x.ApprovalDate == null)
orderby x.AnnualLeaveDate
select new RequestInfo
{
AnnualLeaveDate = x.AnnualLeaveDate,
Forename = x.Employee.Forename,
Surname = x.Employee.Surname,
RequestDate = x.RequestDate,
CancelRequestDate = x.CancelRequestDate,
ApproveFlag = false,
RejectFlag = false,
Reason = string.Empty
}).ToList();
}
}
See how I just removed your from e in db.Employees where ... select e.Forename) and simply replaced it with x.Employee.Forename. When your database contains the correct foreign key relationships, the EF designer will successfully generate a model that contain an Employee property on the AnnualLeaveBooked entity. Writing the query like this makes it much more readable.
I hope this helps.
try this
using (SHPContainerEntities db = new SHPContainerEntities())
{
return db.AnnualLeaveBookeds
.Where(x => x.NextApproverId == _employeeId ||
(x.ApproverId == _employeeId && x.ApprovalDate.HasValue == false))
.Select(y =>
{
var emp = db.Emplyees.Where(e => e.EmployeeId == y.EmployeeId);
return new RequestInfo
{
AnnualLeaveDate = y.AnnualLeaveDate,
Forename = emp.Forename,
Surname = emp.Surname,
RequestDate = y.RequestDate,
CancelRequestDate = y.CancelRequestDate,
ApproveFlag = false,
RejectFlag = false,
Reason = string.Empty
};
).OrderBy(x => x.AnnualLeaveDate).ToList();
}

Resources