I'm trying to join two tables comparing a column of type int with a column of type varchar, but no mather what I try I get some conversion error...
using (Ginkgo5Entities dataContext = new Ginkgo5Entities())
{
var x = (
from node in dataContext.new_users_teams
join udata in dataContext.new_users_data
on new {
x = SqlFunctions.StringConvert((double)node.ID),
y = "team" }
equals new {
x = udata.value,
y = udata.key }
from parent in dataContext.new_users_teams
where node.lft >= parent.lft && node.lft <= parent.rgt && parent.ID == 6
select new {
team = node.team_name
// udata = udata }
).ToList();
}
This throws
"{The specified method 'System.String StringConvert(System.Nullable`1[System.Double])' on the type 'System.Data.Objects.SqlClient.SqlFunctions' cannot be translated into a LINQ to Entities store expression.}"
QUESTIONS:
Is it even possible what I'm trying? If so.. can anyone help
I this a bad practice?
Thank you very much!
Try change this query to :
var x = (from node in dataContext.new_users_teams
join udata in dataContext.new_users_data on node.ID equals udata.value.ToString() and udata.key equals "team" }
from parent in dataContext.new_users_teams
where node.lft >= parent.lft && node.lft <= parent.rgt && parent.ID == 6
Related
I'm trying to fetch the records based on this query
documentList = await (from doc in _dbContext.Documents
join doce in _dbContext.StudentEnrollments on doc.ID equals doce.ID
join enr in _dbContext.Enrollments on doce.EnrollmentID equals enr.Id
where enr.name != null
&& (enr.faiedlattemps = 1 || enr.ReferenceNumber != null)
select doc);
I am getting the
"Correlates the elements of two sequences based on matching key error. The default equality comparer is used to compare keys"
I tried with this as well
var result = from x in _dbContext.Documents
join y in _dbContext.StudentEnrollments
on new { X1 = x.ID } equals new { X1 = y.ID}
join z in _dbContext.Enrollments on new { Z1 = y.EnrollmentID } equals new { Z1 = z.Id}
select new
{
/// Columns
};
Getting the same error
I'm trying to Convert the Uint(i_Customer) to a Nullable Int(i_Customer) ID Since one is accepting the Null value and the other ID Doesn't support.
The parent table is Customer(i_Customer) and the Child is Fault(i_customer). Both, I'm Joining them in a EF Query to get the result. But There is an nullreferenceexception was unhandled by user code Exception that's very disturbing. How Would I fix it?
Here is the EF Query:
if (servicelevel == 3)
{
result = (from s in res
join cInfo in custInfo on
s.fault.i_customer equals Convert.ToInt32((int?)cInfo.customers.i_Customer)
where (s.fault.resolved == null) || (s.tasks.assignedto == agent)
orderby s.fault.ispriority descending, s.fault.logtime ascending
select new ActiveFaultResult()
{ Company_Name = cInfo.customers.Company_Name,
//replies = replies,
idFaults = s.fault.idFaults,
hashvalue = s.fault.hashvalue,
responsible = s.fault.responsible,
logtime = s.fault.logtime,
isinternal = s.fault.isinternal,
ispriority = s.fault.ispriority
}).ToList<ActiveFaultResult>();
// var limitresult = result.Take(50);
return result;
}
A normal cast will do
s.fault.i_customer equals (int?)cInfo.customers.i_Customer
Or try this
s.fault.i_customer ?? 0 equals cInfo.customers.i_Customer
You need to use DefaultIfEmpty() to provide outer join so that it can handle null values. See example below:
result = (from s in res
join cInfo in custInfo on s.fault.i_customer equals (int)cInfo.customers.i_Customer into A
from cInfo in A.DefaultIfEmpty()
where (s.fault.resolved == null) || (s.tasks.assignedto == agent)
orderby s.fault.ispriority descending, s.fault.logtime ascending
select new ActiveFaultResult()
{
Company_Name = cInfo == null? String.Empty: cInfo.customers.Company_Name,
idFaults = s.fault.idFaults,
hashvalue = s.fault.hashvalue,
responsible = s.fault.responsible,
logtime = s.fault.logtime,
isinternal = s.fault.isinternal,
ispriority = s.fault.ispriority
}).ToList<ActiveFaultResult>();
return result;
I have the following SQL statement:
SELECT dh.*
FROM table1 w
LEFT OUTER JOIN table2 dh
on w.CBranch = dh.CBranch
AND w.CWorkstation = dh.CWorkstation
AND w.CNumber = dh.CNumber
RIGHT OUTER JOIN table3 dl
on dh.Id = dl.DispatchHeaderId
AND w.CLine = dl.CLine
AND w.CLineVersion = dl.CVersion
where w.ItemStatus = 9
AND dh.Shipping = 0
ORDER BY dh.CNumber ASC
I am beginner in Linq and not sure how to do advanced linq.
Could someone please guide me writing equivalent linq for this.
I am using C#, EF4.
I have managed to get till here, but not sure f this is correct.
var wos = scope.Context.table1.Where(
a => a.ItemStatus == (short)LineStatus.Packed)
.GroupBy(a => new { a.CNumber, a.CBranch, a.CWorkstation})
.Select(a => a.FirstOrDefault()).ToList();
var headerGroups = new List<IEnumerable<table2>>();
foreach(var status in wos)
{
if (status == null)
{
continue;
}
var headerList = scope.Context.table2s.Where(
b => b.CBranch == status.CBranch &&
b.CNumber == status.CNumber &&
b.CWorkstation == status.CWorkstation).ToList();
if (headerList != null && headerList.Any())
{
headerGroups.Add(headerList);
}
};
use defaultifemty() method in following link way....
http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/
i'm trying to do this on LINQ:
select p.ProductID, p.ArticleCode, SUM((case h.OperationType when 0 then 1 else -1 end) * h.[Count])
from Products p
inner join StockItems s on p.ArticleCode = s.ArticleCode
inner join StockHistorical h on s.ArticleID = h.ArticleID
where h.[Date] < '23/08/2013 11:30:00'
group by p.ProductID, p.ArticleCode
I have this:
var products = (from p in e.Products
join s in e.StockItems on p.ArticleCode equals s.ArticleCode
join h in e.StockHistoricals on s.ArticleID equals h.ArticleID
where h.Date < DateTime.Parse("23/08/2013 11:30:00")
group p by p.ProductID into StockResult
select new { });
Anyone know how can i do the
SUM((case h.OperationType when 0 then 1 else -1 end) * h.[Count])
with LINQ?
Thanks!
I forgot to say that the problem is the "group by", because i can't access the OperationType property in the StockResult group.
Solved! The key is the:
let combined = new
{
Product = p,
HistoryCount = (h.OperationType == 0 ? 1 : -1) * h.Count
}
...
let combined = new
{
Product = p,
HistoryCount = (h.OperationType == 0 ? 1 : -1) * h.Count
}
group combined by combined.Product.ProductID into StockResult
select new
{
ProductID = StockResult.Key,
Total = StockResult.Sum(x => x.HistoryCount)
}
It's not a direct translation, but I'd go with:
(h.Count(his => his.OperationType != 0)
- h.Count(his => his.OperationType == 0))
* h.Count()
It should be functionally equivalent, and seems to better represent what you're trying to do.
You are trying to do something like this?
I am not sure this is going to work.
select new
{
S=Sum(((h.OperationType)!=0?-1:1)*h.Count)
}
I'm writing two LINQ queries where I use my first query's result set in my second query.
But in some cases when there is no data in the database table my first query returns null,
and because of this my second query fails since wsdetails.location and wsdetails.worklocation are null causing an exception.
Exception:
Object reference not set to an instance of an object
My code is this:
var wsdetails = (from assetTable in Repository.Asset
join userAsset in Repository.UserAsset on
assetTable.Asset_Id equals userAsset.Asset_Id
join subLocationTable in Repository.SubLocation on
assetTable.Sub_Location_Id equals subLocationTable.Sub_Location_ID
where userAsset.User_Id == userCode
&& assetTable.Asset_TypeId == 1 && assetTable.Asset_SubType_Id == 1
select new { workstation = subLocationTable.Sub_Location_Name, location = assetTable.Location_Id }).FirstOrDefault();
result = (from emp in this.Repository.Employee
join designation in this.Repository.Designation on
emp.DesignationId equals designation.Id
where emp.Code == userCode
select new EmployeeDetails
{
firstname = emp.FirstName,
lastname = emp.LastName,
designation = designation.Title,
LocationId = wsdetails.location,
WorkStationName = wsdetails.workstation
}).SingleOrDefault();
As a workaround I can check
if wsdetails == null
and change my second LINQ logic, but I believe there are some ways to handle null values in LINQ itself like the ?? operator.
But I tried this and it didn't work for me.
Any help?
The problem is EF can't translate the null-coalescing operator to SQL. Personally I don't see what's wrong with checking the result with an if statement before executing the next query. However, if you don't want to do that, then because your result is always going to be a single query why not do something like:
var wsdetails = (from assetTable in Repository.Asset
join userAsset in Repository.UserAsset on
assetTable.Asset_Id equals userAsset.Asset_Id
join subLocationTable in Repository.SubLocation on
assetTable.Sub_Location_Id equals subLocationTable.Sub_Location_ID
where userAsset.User_Id == userCode
&& assetTable.Asset_TypeId == 1 && assetTable.Asset_SubType_Id == 1
select new { workstation = subLocationTable.Sub_Location_Name, location = assetTable.Location_Id }).FirstOrDefault();
result = (from emp in this.Repository.Employee
join designation in this.Repository.Designation on
emp.DesignationId equals designation.Id
where emp.Code == userCode
select new EmployeeDetails
{
firstname = emp.FirstName,
lastname = emp.LastName,
designation = designation.Title
}).SingleOrDefault();
result.LocationId = wsdetails != null ? wsdetails.location : "someDefaultValue";
result.WorkStationName = wsdetails != null ? wsdetails.workstation ?? "someDefaultValue";
Instead of the "binary" operator ?? maybe you should use the good old ternary one, ? :, like in
wsdetails != null ? wsdetails.location : null
Try not evaluating the first query, and use it in the second query. This should result in a single SQL statement.
var wsdetails = (from assetTable in Repository.Asset
join userAsset in Repository.UserAsset on
assetTable.Asset_Id equals userAsset.Asset_Id
join subLocationTable in Repository.SubLocation on
assetTable.Sub_Location_Id equals subLocationTable.Sub_Location_ID
where userAsset.User_Id == userCode
&& assetTable.Asset_TypeId == 1 && assetTable.Asset_SubType_Id == 1
select new { workstation = subLocationTable.Sub_Location_Name, location = assetTable.Location_Id });
// wsdetails is still an IEnumerable/IQueryable
result = (from emp in this.Repository.Employee
join designation in this.Repository.Designation on
emp.DesignationId equals designation.Id
where emp.Code == userCode
select new EmployeeDetails
{
firstname = emp.FirstName,
lastname = emp.LastName,
designation = designation.Title,
LocationId = wsdetails.First().location,
WorkStationName = wsdetails.First().workstation
}).SingleOrDefault();