linq join code doesn't work - c#

I have 2 records in tblMaterials and zero record in tblMaterialTenderGroups
But when I fetch the data to gridview it shows me the two records, and the join doesn't work
public List<tblMaterial> ShowPresentMaterialInGroup()
{
List<tblMaterial> q = (from i in dbconnect.tblMaterials.AsEnumerable()
join b in dbconnect.tblMaterialTenderGroups on i.materialId equals b.materialId
where b.MaterialGroupId == _materialGroupId
select new tblMaterial()
{
existAmout = i.existAmout,
materialId = i.materialId,
name = i.name,
needAmount = i.needAmount,
requestAmount = i.requestAmount,
unit = i.unit,
requestId = i.requestId
}).ToList();
return q;
}

Can you please try this
List<tblMaterial> q = from i in dbconnect.tblMaterials
join b in dbconnect.tblMaterialTenderGroups on i.materialId equals b.materialId
select new { existAmout = i.existAmout,
materialId = i.materialId,
name = i.name,
needAmount = i.needAmount,
requestAmount = i.requestAmount,
unit = i.unit,
requestId = i.requestId}.ToList();
May be using returning the two records..
I read something here
Using AsEnumerable will break off the query and do the "outside part"
as linq-to-objects rather than Linq-to-SQL. Effectively, you're
running a "select * from ..." for both your tables and then doing the
joins, where clause filter, ordering, and projection client-side.

Related

SQL to LINQ issue

I am working on a composite ranking website. I am trying to query the most recent ranking and the previous ranking side by side.
This query works great in SSMS, but I am unable to make this work in my C# code:
SELECT r.Name, l.RankValue AS currentValue, l.RankDT as CurrentDT, p.RankValue AS prevVal, p.RankDT AS prevDate
FROM RankLookupTB L
JOIN RankingsTB R ON L.RankID = R.RankID
FULL JOIN (SELECT rankid, rankvalue, RankDT FROM RankLookupTB WHERE Obselete = 1 and TeamID = 356) AS P ON l.RankID = p.RankID
WHERE l.TeamID = 356 and Obselete = 0
ORDER BY r.Name
Here is what I have in my Program:
var ranks = from r in _context.RankLookupTbs
where r.TeamId == id && r.Obselete == false
join s in _context.RankingsTbs on r.RankId equals s.RankId
join t in _context.RankLookupTbs on new { id = r.RankId, obsolete = r.Obselete } equals new { id = t.RankId, obsolete = true }
select new { Name = s.Name, CurrentValue = r.RankValue, CurrentDT = r.RankDt, PastValue = t.RankValue, PastDT = t.RankDt };
I am sure that I am not far away from the answer. The join seems to be the problem because I am getting everything in the result set.
Lastly, I downloaded LINQPad, but it is not giving me anything at all.
Thanks for all insights

C# LINQ select from table and join multiple table and join a SQL query view in SQL server

I have a code that selecting from table and joining multiple tables and joining dbContext.Database.sqlQuery from view in sql server.
But it gives me this error
Unable to create a constant value of type
'ITManagement.Models.Employee'. Only primitive types or enumeration
types are supported in this context.
My code
public JsonResult getEmployeeAsset(EmployeeController employee)
{
var employeeID = Request.QueryString["employeeID"];
var devices = (from asset in db.Devices
where asset.EmployeeID == employeeID
join brand in db.DeviceBrands on asset.Brand equals brand.ID
join model in db.DeviceModels on asset.Model equals model.ID
join type in db.DeviceTypes on asset.DeviceType equals type.ID
join room in db.Rooms on asset.FullRoomCode equals room.FullCode
//if device has last employee
join lsEmp in db.Database.SqlQuery<LDAPUsers>("SELECT * FROM V_LDAP_Users") on asset.LastEmployeeID equals lsEmp.employeeID into lstEmp
join sysUser in db.AspNetUsers on asset.sscUser equals sysUser.Id
from lastEmployee in lstEmp.DefaultIfEmpty()
select new
{
deviceID = asset.ID,
SerialNumber = asset.SerialNumber,
Type = type.Type,
BrandName = brand.BrandName,
ModelName = model.ModelName,
MaccCode = asset.MaccCode,
PONumber = asset.PONumber,
WarrantyDate = asset.WarrantyDate.ToString(),
MacAddress = asset.MacAddress,
WIFIMacAddress = asset.WIFIMacAddress,
PCName = asset.PCName,
LastEmployee = asset.LastEmployeeID + "-" + lastEmployee.employeeName,
Shared = asset.Shared == 1 ? "True" : "False",
Location = room.RoomName,
RecordedBy = sysUser.Name,
requestID = (from request in db.StoreRequests where request.DeviceID == asset.ID && request.State == 1 && request.VoucherType == "ASD" orderby request.ID select request.ID).FirstOrDefault()
}).DefaultIfEmpty();
return Json(new { assets = devices == null ? null : devices }, JsonRequestBehavior.AllowGet);
}
Your help please, thanks.
First of all, have you tried nested queries by commenting them out?
for example;
//join lsEmp in db.Database.SqlQuery<LDAPUsers>("SELECT * FROM V_LDAP_Users") on asset.LastEmployeeID equals lsEmp.employeeID into lstEmp
//requestID = (from request in db.StoreRequests where request.DeviceID == asset.ID && request.State == 1 && request.VoucherType == "ASD" orderby request.ID select request.ID).FirstOrDefault()
If there is no problem in these two, you can quickly find out which one is causing the problem by commenting the fields.
Tip: Also, more than 3 joins will affect your query performance. Try to split your queries as much as possible.

MongoDb aggregate in c#

I need to join 3 collections and get the desired data. I have written a LINQ query which working fine but I want to write it using mongoDb's Aggregate interface.
Here is my query in LINQ.
var query = from user in userCollection.AsQueryable()
where user.Id == userId
from userDivision in user.Divisions
select new { userDivision.DivisionId } into divisions
join division in divisionCollection.AsQueryable() on divisions.DivisionId equals division.Id
select new { division.CompanyId } into divisionCompany
join company in companyCollection.AsQueryable() on divisionCompany.CompanyId equals company.Id
select new
{
company.Id,
company.Code,
company.Name,
company.Address,
ConcurrencyId = "1_" + "3_" + company.Id
} into c
join concurrency in concurrencyCollection.AsQueryable() on c.ConcurrencyId equals concurrency.Id into concurrencies
from concurrencyEmpty in concurrencies.DefaultIfEmpty()
select new Response.Company
{
Id = c.Id,
Code = c.Code,
Name = c.Name,
CodeAndName = c.Code + " - " + c.Name,
Address = c.Address,
ConcurrencyVersion = concurrencyEmpty.Version
};
Can anybody tell me how to write this query using MongoDb's aggregate interface (using LookUp etc).
Thanks in advance.

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method

I wrote this SQL query
select
acc.DepartmentID,
dept.DepartmentName,
dept.DepartmentDivision,
county.CountyName,
sp.StateProvinceID
from [AccountDepartmentXREF] acc
inner join [Department] dept on dept.DepartmentID = acc.DepartmentID
left join [DepartmentStateCountyXREF] dscx on dscx.DepartmentID = acc.DepartmentID
left join [StateCounty] county on county.StateCountyID = dscx.StateCountyID
inner join [StateProvince] sp on sp.StateProvinceID = dept.StateProvinceID
where acc.AccountID = 1
and want to rewrite it using LINQ, but I always get confused when writing left joins in LINQ, so I decided to use a convertor and went with Linqer and this is what it produced
from acc in db.AccountDepartmentXREF
join dscx in db.DepartmentStateCountyXREF on acc.DepartmentID equals dscx.DepartmentID into dscx_join
from dscx in dscx_join.DefaultIfEmpty()
join county in db.StateCounty on new { StateCountyID = Convert.ToInt32(dscx.StateCountyID) } equals new { StateCountyID = county.StateCountyID } into county_join
from county in county_join.DefaultIfEmpty()
join sp in db.StateProvince on acc.Department.StateProvinceID equals sp.StateProvinceID
where
acc.AccountID == 1
select new {
acc.DepartmentID,
acc.Department.DepartmentName,
acc.Department.DepartmentDivision,
CountyName = county.CountyName,
sp.StateProvinceID
}
so when I put everything together in code
public List<DepartmentList> GetDepartmentsByAccountID(string email)
{
HWC = new HWCEntities();
List<DepartmentList> result = new List<DepartmentList>();
int id = CurrentUserID(email);
List<AccountDepartmentXREF> adx = HWC.AccountDepartmentXREFs.Where(w => w.AccountID == id).ToList();
foreach(var a in adx)
{
var query = from acc in HWC.AccountDepartmentXREFs
join dscx in HWC.DepartmentStateCountyXREFs on acc.DepartmentID equals dscx.DepartmentID into dscx_join
from dscx in dscx_join.DefaultIfEmpty()
join county in HWC.StateCounties on new { StateCountyID = Convert.ToInt32(dscx.StateCountyID) } equals new { StateCountyID = county.StateCountyID } into county_join
from county in county_join.DefaultIfEmpty()
join sp in HWC.StateProvinces on acc.Department.StateProvinceID equals sp.StateProvinceID
where
acc.AccountID == a.AccountID
select new
{
acc.DepartmentID,
acc.Department.DepartmentName,
acc.Department.DepartmentDivision,
CountyName = county.CountyName,
sp.StateProvinceID
};
foreach(var b in query)
{
result.Add(new DepartmentList
{
DepartmentID = b.DepartmentID,
DepartmentName = b.DepartmentName,
StateProvinceID = b.StateProvinceID,
DivisionName = b.DepartmentDivision,
CountyName = b.CountyName
});
}
}
return result;
}
I get the error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression.
at the
foreach(var b in query)
Any idea's on how to fix this? I have looked around but other solutions I found aren't dealing with joins
Linq doesn't support the Convert.ToInt32(dscx.StateCountyID) method inside the query because this will need to be converted to sql for execution on the db.
I am not sure what datatype StateCountyID is in both tables but you will need to use some sql compatible conversion method like SqlFunctions.StringConvert() to get them to the same datatype.
Convert them to Strings
from acc in HWC.AccountDepartmentXREFs
join dscx in HWC.DepartmentStateCountyXREFs on acc.DepartmentID equals dscx.DepartmentID into dscx_join
from dscx in dscx_join.DefaultIfEmpty()
join county in HWC.StateCounties on new { StateCountyID = dscx.StateCountyID.ToString() } equals new { StateCountyID = county.StateCountyID.ToString() }
or use the below:
dscx.StateCountyID equals SqlFunctions.Convert(county.StateCountyID)
I figured out why I was getting that error. It was because I had StateCountyID as nullable in my DepartmentStateCountyXREF table. Once I changed the StateCountyID column from a nullable and then removed the Convert.ToInt32, everything worked.

LINQ query to get count of records

I'm trying to retrieve some records from database along with a count, with LINQ.
DataTable dtByRecipe = (from tbrp in context.tblRecipeParents
join tbrc in context.tblRecipeChilds on tbrp.RecipeParentID equals tbrc.RecipeParentID
join tbp in context.tblProducts on tbrc.ProductID equals tbp.ProductID
join tbps in context.tblProductSales.AsEnumerable()
on tbp.ProductID equals tbps.ProductID
join tbs in context.tblSales.AsEnumerable()
on tbps.ProductSalesID equals tbs.ProductSalesID select new
{
tbrp.Recipe,
tbp.ProductID,
tbps.ProductSalesID,
tbrp.Yield,
Product = tbp.ProductCode + " - " + tbp.ProductDescription,
ProductYield = tbrp.Yield,
TotalYield = "XXX",
Cost = "YYY"
}).AsEnumerable()
.Select(item => new {
item.Recipe,
Count = GetCount(item.ProductID, item.ProductSalesID, context),
item.Yield,
Product = item.Product,
ProductYield = item.ProductYield,
TotalYield = "XXX",
Cost = "YYY"
}).OrderBy(o => o.Recipe).ToDataTable();
private int GetCount ( int ProductID, int ProductSalesID, MTBARKER_DBEntities context )
{
int query = ( from tbps in context.tblProductSales
join tbp in context.tblProducts on tbps.ProductID equals tbp.ProductID
join tbs in context.tblSales
on tbps.ProductSalesID equals tbs.ProductSalesID
where tbp.ProductID == ProductID && tbps.ProductSalesID == ProductSalesID
select tbs ).Count();
return query;
}
In above query I get the expected result but since there are around 10K records in the database it consumes a lot of time to produce the result. The issue is with the following approach I have used to get the count.
Count = GetCount(item.ProductID, item.ProductSalesID, context),
Is there any productive way that I could prevent this issue?
Well Stored Procedures is best choice for performance.Use Stored Procedures in the Entity Framework for selection and for reporting.

Categories