Nested LINQ query using Contains with a bigint - linq

This is the SQL I want (ClearinghouseKey is a bigint):
select *
from ConsOutput O
where O.ClearinghouseKey IN (
select distinct P.clearinghouseKey
from Project P
Inner join LandUseInProject L on L.ClearinghouseKey = P.ClearinghouseKey
where P.ProjectLocationKey IN ('L101', 'L102', 'L103')
and L.LandUseKey IN ('U000', 'U001', 'U002', 'U003')
)
The inner query is straight forward and gives correct results in LINQPad:
var innerQuery = (from p in Projects
join l in LandUseInProjects on p.ClearinghouseKey equals l.ClearinghouseKey
where locations.Contains(p.ProjectLocationKey)
&& (landuses.Contains(l.LandUseKey))
select new { p.ClearinghouseKey }).Distinct();
But the outer query gives the error: Type arguments from ...Contains..cannot be inferred from usage:
var returnQuery = from o in OperOutput
where (innerQuery).Contains(o.ClearinghouseKey)
select o;
Is it because ClearinghouseKey is a bigint? Any other ways to write this query?
Thanks,
Jeanne

Don't use an anonymous type:
select new { p.ClearinghouseKey })
Should be
select p.ClearinghouseKey)
Also consider using Any instead of Contains (I don't have reasons for choosing one over the other, yet).
where innerQuery.Any(i => i == o.ClearinghouseKey)

Related

Linq Group by / Distinct with Join table

i plan to join 2 table, and get the distinct value of language column. How should i achieve that in Linq? I try add 'group' but no luck. Besides, i want to select s value too together with r distinct language value.
My code:
public ActionResult QuestionLink(int Survey_ID)
{
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group r.language << this is not work **
select r;
return PartialView(query.ToList());
}
This is what in MoreLinq is called DistinctBy. But if that method works on IEnumerable, so you can't use it in an EF query. But you can use the same approach:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.language into grp
select grp.FirstOrDefault();
But I wonder if this really is what you want. The result depends on the ordering of languages that the database happens to return. I think you should add a predicate for a specific language and remove the grouping:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
&& r.language == someVariable
select new { r, s };
You can do like this:
var query = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new {r, s} by r.language into rg
select rg.Key;

Linq 2 SQL left Join with mono

I cant get the fallowing request working in Mono:
Without joins it would work.
when I only select t1 it also works, but I cant select something from both tables.
I think I want a left join, where I always have entries in t1 and IF the NameOfFile matches FileName then I want to have the tables joined.
Extra Question: When is my query executed? When I run the foreach loop?
var result = (
from t1 in db.Table1
join t2 in db.Table2 on t1.FileName equals t2.NameOfFile
into joinDep
from t3 in joinDep.DefaultIfEmpty ()
select new
{
Time = t1.WriteTime,
Name = t2.NameOfFile
}
)
.OrderByDescending (c => c.Time.Date)
.Take (10);
foreach (var entry in result)
{
Console.WriteLine (entry.Name );
}
Use this:
var query = from t1 in db.Table1
join t2 in db.Table2 on t1.FileName equals t2.NameOfFile into gj
from joinDep in gj.DefaultIfEmpty ()
select new
{
Time = t1.WriteTime,
Name = joinDep.NameOfFile
};
var result = query.OrderByDescending (c => c.Time.Date)
.Take (10);
Yes. Take uses deferred execution.

Join statement in Linq to Sql

I need to write Join statment after writing query in linq
example :
var Query = (from Tab in Db.Employees
select Tab)
as i have some cases to perform join operation so
i need to do it on this Query Query.Join(Join with another Table like Department); I need the Syntax
if (DeptID != -1){ Query.Join(Join with table Department where FkDeptID = DeptID); }
Consider the usage of join in the LINQ 'query syntax':
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
Something like this?
var results = (from q in Query
join m in myList on q.SomeID = m.SomeID
select unknown);
Try using this query:
var Query =
from e in Db.Employees
join d in Db.Departments on e.FkDeptID equals d.DeptID into departments
select new
{
Employee = e,
Department = departments.SingleOrDefault(),
};
This works assuming that when e.FkDeptID == -1 that there is no record in the Departments table and in that case Department would be assigned null.
You should never have more than one department for an employee so I've used SingleOrDefault rather than FirstOrDefault.

Group by, Sum, Join in Linq

I have this simple sql query:
select c.LastName, Sum(b.Debit)- Sum(b.Credit) as OpenBalance from Balance as b
inner join Job as j on (b.Job = j.ID)
inner join Client as c on (j.Client = c.ID)
Group By c.LastName
and I am trying to convert it to work in linq like this:
from b in Balance
join j in Job on b.Job equals j.ID
join c in Client on j.Client equals c.ID
group b by new { c.LastName } into g
select new {
Name = c.Lastname,
OpenBalance = g.Sum(t1 => t1.Credit)
}
but when I try to run it in LINQPad I get the following message:
The name 'c' does not exist in the
current context
and it highlights c.Lastname in select new statement.
Any help on this will be greatly appreciated.
Thank you.
Well, you've grouped b by c.LastName. So after the grouping operation, you're dealing with g which is a grouping with the element type being the type of b, and the key type being the type of c.LastName. It could well be that all you need is:
select new {
Name = g.Key,
OpenBalance = g.Sum(t1 => t1.Credit)
}
... but if you need to get at any other aspects of c, you'll need to change your grouping expression.

Join in linq: "The specified LINQ expression contains references to queries that are associated with different contexts."

Is it possible to make a join in linq and only return data from one dataset where the other key was present, a little like:
var q = from c in customers
join o in orders on c.Key equals o.Key
select new {c.Name, o.OrderNumber};
and then instead of returning just the two records then returning customers like:
var q = from c in customers
join o in orders on c.Key equals o.Key
select c;
When I try to do (something similar) I get this error:
The specified LINQ expression contains references to queries that are associated with different contexts.
I going to assume that you've skipped a Where clause which involved the orders table (or otherwise the join would be pointless)
In which case, you can just have Linq infer the join.
var q = from c in customers
where c.Orders.Any(o=> o.ProductCode == productCode)
select c;
Linq2Sql will automatically create the Orders property if you have a foreign key defined; I believe with the Entity Framework, you have to manually specify it.
The error indicates an other problem:
You have to use the same DataContext on every object in the query if you're using Linq to SQL.
Your code should look somehow like that:
using (MyDataContext dc = new MyDataContext())
{
var q = from c in dc.customers
join o in dc.orders on c.Key equals o.Key
select c;
// process q within the DataContext
// the easies would be to call q.ToList()
}
Will it be in EF 4.0 to create join from multiple context?
For example:
TestModelEntities e1 = new TestModelEntities();
TestModelEntities e2 = new TestModelEntities();
var d = from firme1 in e1.firme
join g in e2.grad on firme1.grad.grad_id equals g.grad_id
select firme1;

Resources