I have a list as follows:
List<int> loc = new List<int>();
which I populate.
Note that the list stores int values.
I like to join this list to a db table as follow.
What I need to do is something like:
var result = (from pc in db.loc_details
join l in loc
on pc.locid = loc
select pc).ToList();
I get an error obviously: Cannot implicitly convert type 'System.Connection.Generics.List to 'int'.
What is the best approach to do this?
You're trying to join a single int to the entire list.
Try
var result = (from pc in db.loc_details
join l in loc
on pc.locid equals l
select pc).ToList();
although that will gve you a different error if you are using EF since it can't translate a join to an in-memory list to SQL. If that is the case, you can use Contains which gets translated to an IN clause:
var result = (from pc in db.loc_details
where loc.Contains(pc.locid)
select pc).ToList();
You wrote:
List<int> loc = new List<int>();
var result = (from pc in db.loc_details
join l in loc
on pc.locid = loc
select pc);
Answer yourself: what is the type of pc.LocId? And what is the type of loc?
Now look at your code:
on pc.locid = loc
by the way, shouldn't the = be equals or at least ==?
Related
Kindly convert my SQL to LINQ. I'm really desperate. It includes multiple filtering (2).
SELECT dbo.EmployeeAccess.EmpNo,
dbo.View_SystemAdminMembers.LNameByFName,
dbo.View_SystemAdminMembers.GroupName,
dbo.View_SystemAdminMembers.Role,
dbo.View_SystemAdminMembers.Active,
dbo.View_SystemAdminMembers.EmpNo AS Expr4,
dbo.View_SystemAdminMembers.RoleID
FROM dbo.EmployeeAccess
INNER JOIN dbo.View_SystemAdminMembers
ON dbo.EmployeeAccess.GroupID = dbo.View_SystemAdminMembers.GroupID
WHERE (dbo.EmployeeAccess.EmpNo = '50')
Thank you so much in advance.
Please try with the below code snippet.
var result =from e in context.EmployeeAccess
join v in context.View_SystemAdminMembers on e.GroupID equals v.GroupID
Where e.EmpNo == 50
select new { e.EmpNo,v.LNameByFName,v.GroupName,v.Role,v.Active,a.RoleID,v.EmpNo as VEmpNo };
Note : context is your DB Context object.
Let me know if any concern.
var results = (from ea in DbContext.EmployeeAccess
join sam in DbContext.View_SystemAdminMembers on ea.GroupId equals sam.GroupId
where ea.EmpNo = '50'
select new {
ea.EmpNo,
sam.LNameByFName,
sam.GroupName,
sam.Role,
sam.Active,
Expr4 = sam.EmpNo,
sam.RoleID
};
You didnt mention what your database context was, you'll have to fill that in yourself.
var res = (from x in ctx.EmployeeAccess
join y in ctx.View_SystemAdminMembers on x.GroupId equals y.groupId
where x.EmpNo = '50'
select new
{
x.EmpNo,
y.LNameByFName,
y.GroupName,
y.Role,
y.Active,
Expr4 = y.EmpNo,
y.RoleID
});
Note: do NOT use = when joining, but equals.
My code is:
using( var ctxA = new AEntities())
using( var ctxB = new BEntities())
{
var listOfA = (from A in AEntities.AEntity select A).ToList();
var listOfB = (from B in BEntities.BEntity
where listOfA.Select( A = A.Id)contains(B.Id)
select B).ToList();
}
I'm getting the error:
The specified LINQ expression contains references to queries that are associated with different contexts.
However, because of 'ToList' I already did a fetch in AEntity thats makes second query only about one of the contexts, did not?
How can a separate the two queries still using one list to query the other?
Try to store just IDs into listOfA
var listOfA = (from A in AEntities.AEntity select A.Id).ToList();
var listOfB = (from B in BEntities.BEntity
where listOfA.Contains(B.Id)
select B).ToList();
If anyone wants to know, the answer to my question was:
var listOfA = (from A in AEntities.AEntity select A.Id).ToList();
List<long> listOfIdsOfA = listOfA.Select( A=>A.id).ToList();
var listOfB = (from B in BEntities.BEntity
where listOfIdsOfA.Contains(B.Id)
select B).ToList();
The only difference to Selman's answer was the creation of Id's list after the first query. That's why I need the whole entity too.
er have the following query in linq...
Whenever I try to run it I get a No comparison operator for type System.Int[] exception.
It's got something to do with the dictionary I am sure, but I don't understand why this isn't valid and was wondering if someone could explain?
// As requested... not sure it will help though.
var per = (
from p in OtherContext.tblPeriod
where activeContractList.Select(c => c.DomainSetExtensionCode).Contains(p.DomainSetExtensionCode)
select p).ToArray();
var com = (
from c in MyContext.tblService
join sce in MyContext.tblServiceExtension
on c.ServiceExtensionCode equals sce.ServiceExtensionCode
join sc in MyContext.tblServiceContract
on sce.ServiceContractCode equals sc.ContractCode
group sc by c.Period into comG
select new
{
PeriodNumber = comG.Key,
Group = comG,
}).ToArray();
var code =
(from c in com
join p in per on c.PeriodNumber equals p.PeriodNumber
select new
{
p.Code,
c.Group
}).ToArray();
var payDictionary = new Dictionary<int, int[]>();
// This is another linq query that returns an anonymous type with
// two properties, and int and an array.
code.ForEach(c => payDictionary.Add(c.Code, c.Group.Select(g => g.Code).ToArray()));
// MyContext is a LINQ to SQL DataContext
var stuff = (
from
p in MyContext.tblPaySomething
join cae in MyContext.tblSomethingElse
on p.PaymentCode equals cae.PaymentCode
join ca in MyContext.tblAnotherThing
on cae.SomeCode equals ca.SomeCode
where
// ca.ContractCode.Value in an int?, that should always have a value.
payDictionary[p.Code].Contains(ca.ContractCode.Value)
select new
{
p.Code,
p.ExtensionCode,
p.IsFlagged,
p.Narrative,
p.PayCode,
ca.BookCode,
cae.Status
}).ToList();
You won't be able to do this with a dictionary. The alternative is to join the three linq queries into one. You can do this with minimal impact to your code by not materializing the queries with ToArray. This will leave com and code as IQueryable<T> and allow for you compose other queries with them.
You will also need to use a group rather than constructing a dictionary. Something like this should work:
var per = (
from p in OtherContext.tblPeriod
where activeContractList.Select(c => c.DomainSetExtensionCode).Contains(p.DomainSetExtensionCode)
select p.PeriodNumber).ToArray(); // Leave this ToArray because it's materialized from OtherContext
var com =
from c in MyContext.tblService
join sce in MyContext.tblServiceExtension on c.ServiceExtensionCode equals sce.ServiceExtensionCode
join sc in MyContext.tblServiceContract on sce.ServiceContractCode equals sc.ContractCode
group sc by c.Period into comG
select new
{
PeriodNumber = comG.Key,
Group = comG,
}; // no ToArray
var code =
from c in com
where per.Contains(c.PeriodNumber) // have to change this line because per comes from OtherContext
select new
{
Code = c.PeriodNumber,
c.Group
}; // no ToArray
var results =
(from p in MyContext.tblPaySomething
join cae in MyContext.tblSomethingElse on p.PaymentCode equals cae.PaymentCode
join ca in MyContext.tblAnothThing on cae.SomeCode equals ca.SomeCode
join cg in MyContext.Codes.GroupBy(c => c.Code, c => c.Code) on cg.Key equals p.Code
where cg.Contains(ca.ContractCode.Value)
select new
{
p.ContractPeriodCode,
p.DomainSetExtensionCode,
p.IsFlagged,
p.Narrative,
p.PaymentCode,
ca.BookingCode,
cae.Status
})
.ToList();
Side Note: I also suggest using navigation properties where possible instead of joins. It makes it much easier to read and understand how objects are related and create complex queries.
I have the following LINQ query:
vm.Ter = (from tr in DataContext.Terr_Rp
join dm in DataContext.Dt_Mrs
on tr.T_ID equals dm.D_ID + "00"
select tr).ToList();
I need to find the ones that do not have a match. Meaning there is no join.
I tried not equals but C# has a problem with it.
Using !Any() should do the trick.
vm.Ter = (from tr in DataContext.Terr_Rp
where !DataContext.Dt_Mrs.Any(dm => tr.T_ID == dm.D_ID + "00")
select tr).ToList();
var list1 = new List<int>{1,2,3,4,5,6};
var list2 = new List<int>{5,6,7,8,9,10};
var result = from l1 in list1 where !list2.Contains(l1) select l1;
result: {1,2,3,4}
Is there somebody that could translate this query to Linq in C# . I was searching and I didn't find any query similiar to.
Thanks a lot guys!
SQL Sentence:
SELECT a.Amenaza, c.Nombre, c.Descripcion
FROM AmenazasEstablecer a, ControlesEstablecer c, Matriz_Amenazas_ControlesEstablecer m
WHERE a.IdAmenaza = m.IdAmenaza AND c.IdControl=m.IdControl;
You will have to have a DataContext created and specified, but once you do you could get away with:
MyDataContext context = new MyDataContext("SomeConnectionString");
var results = from a in context.AmenazasEstablecer
from c in context.ControlesEstablecer
from m in context.Matriz_Amenazas_ControlesEstablecer
where a.IdAmenaza == m.IdAmenaza && c.IdControl == m.IdControl
select new {
a.Amenaza,
c.Nombre,
c.Descripcion
});
var results = from a in context.AmenazasEstablecer
join m in context.Matriz_Amenazas_ControlesEstablecer
on a.IdAmenaza equals m.IdAmenaza
join c in context.ControlesEstablecer
on c.IdControl equals m.IdControl
select new {a.Amenaza, c.Nombre, c.Descripcion};