I have the table structure as below,
I need the result like :
Redbook
|______Wedding
|______Christian
|______Muslim
|______Hindu
|______Birthday
|______Baptism
Which means, parentID having 0 should be the root and who's id(here 1) as parentID are its children (ie., wedding,birthday,Baptism) and so on...
I tried something like:
public List<specdetails> getProductDet(int ID)
{
List<specdetails> result;
using (APM context = new APM())
{
var res = (from s in context.M_CategoryDetails where s.CategoryID == ID select s).ToList();
result = res
.GroupBy(u=>u.ParentID)
.Select(grp => new specdetails
{
parentID = (int)grp.Key,
//ImageList = grp.ToList()
description = grp.FirstOrDefault().Description,
ID = grp.FirstOrDefault().ID,
catID = (int)grp.FirstOrDefault().CategoryID,
vPath = grp.FirstOrDefault().VirtualPath
}
).ToList();
}
return null; //result;
}
But it does not accomplish my needs.Please help.
Related
I am trying to query my database to return turn reports with any attachments included. I need a list of turn report items which are returned by date, and then for each report I want it to also return all of the attachments associated with the turn reports. The only way to associate them is by the EntryId.
Here is my method to get the turn reports:
public List<TurnReportItem> GetTurnReportsByDateShiftAndDept(DateTime shiftStart, int shiftNum, int dept)
{
try
{
List<TurnReportItem> list;
using (connection)
{
list = (from r in connection.VTurnReports
join a in connection.TurnReportAreas on r.AreaId equals a.AreaId
where a.DeptId == dept && a.Enabled && r.ShiftDate == shiftStart && r.ShiftNum == shiftNum
select new TurnReportItem
{
areaId = r.AreaId,
areaName = a.Name,
author = r.Author,
comment = r.Comment,
datetime = r.Datetime,
id = r.EntryId,
ip = r.Ip,
shiftDate = r.ShiftDate,
shiftNum = r.ShiftNum,
sort_order = a.SortOrder,
attachment_count = r.AttachmentCount,
attachments = (
from at in connection.TurnReportAttachments where at.EntryId == r.EntryId
select new TurnReportAttachment
{
AttachmentId = at.AttachmentId,
FileName = at.FileName
}).ToList()
})
.OrderBy(r => r.sort_order)
.OrderBy(r => r.datetime)
.ToList();
return list;
}
}
Here is the TurnReportItem class that I am filling. If I do not have the subquery I do get all of the turnreports.
public class TurnReportItem
{
public int id;
public string comment;
public DateTime datetime;
public string author;
public int areaId;
public string areaName;
public DateTime shiftDate;
public int shiftNum;
public string ip;
public int? attachment_count;
public int sort_order;
public int area_rating;
public List<TurnReportAttachment> attachments;
public TurnReportItem() { }
}
I have a separate method that will return the all of the comments with the entry id. I have tried to fill the list using that method. I am converting this from a MVC app and I was able to use the method to fill the list however it will not work when I try it in this app, I also would prefer to only make one connection in the database to get what I need.
List<TurnReportItem> list;
using (connection)
{
list = (from r in connection.VTurnReports
join a in connection.TurnReportAreas on r.AreaId equals a.AreaId
where a.DeptId == dept && a.Enabled && r.ShiftDate == shiftStart && r.ShiftNum == shiftNum
select new TurnReportItem
{
areaId = r.AreaId,
areaName = a.Name,
author = r.Author,
comment = r.Comment,
datetime = r.Datetime,
id = r.EntryId,
ip = r.Ip,
shiftDate = r.ShiftDate,
shiftNum = r.ShiftNum,
sort_order = a.SortOrder,
attachment_count = r.AttachmentCount,
attachments = SelectAttachmentsByEntryId(r.EntryId)
})
.OrderBy(r => r.sort_order)
.OrderBy(r => r.datetime)
.ToList();
return list;
}
public List<TurnReportAttachment> SelectAttachmentsByEntryId(int EntryId)
{
using (connection)
{
// we do it this way so that we don't return the blob
var results = from p in connection.TurnReportAttachments
where p.EntryId == EntryId
select new TurnReportAttachment
{
EntryId = p.EntryId,
AttachmentId = p.AttachmentId,
FileName = p.FileName
};
return results.ToList();
}
}
In your case SelectAttachmentsByEntryId should be static, with additional parameter connection. To make it work, it is needed to use ExpressionMethod.
public static class ReportHelpers
{
[ExpressionMethod(nameof(SelectAttachmentsByEntryIdImpl))]
public static List<TurnReportAttachment> SelectAttachmentsByEntryId(MyConnection connection, int EntryId)
{
throw new InvalidOperationException(); // should never enter here
}
private static Expression<Func<MyConnection, int, List<TurnReportAttachment>>> SelectAttachmentsByEntryIdImpl()
{
return (connection, EntryId) =>
(from p in connection.TurnReportAttachments
where p.EntryId == EntryId
select new TurnReportAttachment
{
EntryId = p.EntryId,
AttachmentId = p.AttachmentId,
FileName = p.FileName
})
.ToList();
}
}
Then you can use this method in queries:
public List<TurnReportItem> GetTurnReportsByDateShiftAndDept(DateTime shiftStart, int shiftNum, int dept)
{
using (connection)
{
var list = (from r in connection.VTurnReports
join a in connection.TurnReportAreas on r.AreaId equals a.AreaId
where a.DeptId == dept && a.Enabled && r.ShiftDate == shiftStart && r.ShiftNum == shiftNum
select new TurnReportItem
{
areaId = r.AreaId,
areaName = a.Name,
author = r.Author,
comment = r.Comment,
datetime = r.Datetime,
id = r.EntryId,
ip = r.Ip,
shiftDate = r.ShiftDate,
shiftNum = r.ShiftNum,
sort_order = a.SortOrder,
attachment_count = r.AttachmentCount,
attachments = ReportHelpers.SelectAttachmentsByEntryId(connection, r.EntryId)
})
.OrderBy(r => r.sort_order)
.ThenBy(r => r.datetime)
.ToList();
return list;
}
}
Note that OrderBy.OrderBy has no sense. It should be OrderBy.ThenBy
I have the following SQL query that returns the results I need:
SELECT
STAFF_ID
FROM [dbo].[StaffTable]
WHERE STAFF_ID NOT IN (SELECT STAFF_ID
FROM [dbo].[StaffingTable]
WHERE [DATE] = #DATE
AND MODEL_ID = #Model)
I have the following controller method to try and return the correct results:
public JsonResult GetStaffResults(DateTime date, string modelId)
{
Guid modelGuid = Guid.Parse(modelId);
var settings = new JsonSerializerSettings();
var staff = context.StaffTable.Select(c => new
{
Id = c.StaffId,
Name = c.StaffName
});
var staffing = context.StaffingTable.Select(c => new
{
modelId = c.ModelId,
manufacturerId = c.ManufacturerId,
staffId = c.StaffId,
date = c.Date,
recordId = c.RecordId
});
var staffResults = staff.Where(p => staffing.Select(o => o.modelId).First() == modelGuid && !staffing.Select(o => o.date).Contains(date));
return Json(shiftResults, settings);
}
However, I'm struggling with the Lambda expression, it returns no results so I've missed something somewhere.
You can try something like this:
public JsonResult GetStaffResults(DateTime date, string modelId)
{
Guid modelGuid = Guid.Parse(modelId);
var settings = new JsonSerializerSettings();
var staffQuery = context.StaffTable
.Where(s => !context
.StaffingTable
.Any(st => st.StaffId = s.StaffId && st.modelId == modelGuid && st.date == date))
.Select(c => new
{
Id = c.StaffId,
Name = c.StaffName
});
return Json(staffQuery.ToList(), settings);
}
You are doing separate query with Select which has a performance issue as the queries will return IEnumerable<T> objects. If you want to have separate queries then try to get the query results as IQueryable<T> which will construct the queries and will load data at the end.
For example:
var query =
from st in context.StaffTable
where !(from stff in context.StaffingTable
select stff.CustomerID)
where stff.MODEL_ID = ModelIdVariable AND stff.DATE = DATEVariable
.Contains(st.CustomerID)
select st;
Declare and populate the ModelIdVariable and DATEVariable variables before the query.
Then you can do query.ToList<T>() where you need the data to be loaded.
I am still getting familiar with SQL and LINQ and I am trying to get every objects and its objects which is under one ID.
The below is the EDMX Diagram.
I am passing ClientID and I want to list everything that is under that ClientID and the below is my query to do so but as you can see query is only returning the first element but how to change it to return the list of every elements as below:
Passed ClientID
THeaderTitle 1
TReportName 1
TReportName 2
MY query is below which is returning the first element:
public TReportHeaderModel GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
}).First();
return query;
}
}
I've got it working!
I had to change it in my interface as
IList GetHeadersByClient (int ClientID);
So that I can return List of elements in my controller to pass to view.
public IList<TReportHeaderModel> GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
});
return query.ToList();
}
}
I have two lists of same type with different key value pairs,
List1 has "isPermanent = true" and List2 has false value and also
List1 has an extra key "nextVacationDate".
Im trying to do union of these as below but im afraid I will still get the duplicates because of different values. I need to merge both lists in to one list and order by List1 first (Permanent employees first)..is there a better way to do this using LINQ?
public newList1 List1(string abcd)
{
var result = serviceMethod1(abcd);
var newList1 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = true,
nextVacationDate =x.VacDt,
salary = x.Bsalary
}));
return newList1;
}
public newList2 List2(string defg)
{
var result = serviceMethod2(defg);
var newList2 = new List<emp>();
if (result == null) return null;
newList.AddRange(
result.Select(x => new Model
{
firstName = x.FName,
secondName = x.SName,
address = x.Address,
employeeId = x.EmpId,
isPermanent = false,
salary = x.Bsalary
}));
return newList2;
}
private List<emp> EmployyeList(List<emp> newList1, List<emp> newList2)
{
var sortedEmpList1 = newList1.OrderBy(i => i.Fname);
var sortedEmpList2 = newList2.OrderBy(i => i.Fname);
List<MeterModel> combinedList = newList1.Union(newList2) as List<emp>;
return combinedList;
}
You can filter the 2nd list to avoid duplicates:
newList1.Union(newList2.Where(emp2 => !newList1.Any(emp1 => emp1.employeeId == emp2.employeeId)))
I was trying to get employee list which not already available in another list. but im getting only first element from array list.
ex : if i try EmployeeId = new int[2] {5, 2}; the list excluding only '5'. So please help me correct my below code.
public JsonResult GetEmployees(int[] EmployeeId)
{
var dbs = new dbContext();
if (EmployeeId != null)
{
foreach (var emp in EmployeeId)
{
var EmpList = dbs.Employees.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
}).Where(o => o.EmployeeId != emp);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
}
return null
}
Try this :
var employeeList = dbs.Employees.
.Where(e => EmployeeId.All(x=> x != e.EmployeeId))
.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
});
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
Have you tried stepping through your code?
Your foreach iterates over your EmployeeId array.
Since you have a return statement in your foreach it exits the function at that point and it only uses the first element of your array.
You need something like this:
public JsonResult GetEmployees(int[] EmployeeId)
{
var dbs = new dbContext();
if (EmployeeId != null)
{
var EmpList = dbs.Employees.Where(EmployeeId.Contains(e.EmployeeId))
.Select(e => new
{
EmployeeId = e.EmployeeId,
Name = e.EmployeeName,
Job = e.Job.JobName,
Currency = e.Currency.CurrencyName,
Amount = e.Amount
}).Where(o => o.EmployeeId != emp);
return Json(EmpList, JsonRequestBehavior.AllowGet);
}
return null;
}