Can I use this query in the entity 4.0 framework? - linq

I'm needing some syntax help with the following query please? I'd like to use an equivalent in the entity framework but I'm unsure of the syntax.
Can someone help me format this to work with the entity framework?
Thanks in advance.
Select * from (
SELECT [Member]
,[MemberGroup],
(SELECT [text]
FROM [umbracoNode]where [id] = [Member]) As MemberName,
(SELECT [text]
FROM [umbracoNode]where [id] = [MemberGroup]) As GroupName
FROM [cmsMember2MemberGroup]
) UG
where UG.MemberName is not null
order by UG.MemberName,
UG.GroupName

Try this:
var query =
from x in db.cmsMember2MemberGroup
join y in db.umbracoNode on x.Member equals y.id
let MemberName = y.text
where MemberName != null
join z in db.umbracoNode on x.MemberGroup equals z.id
let GroupName = z.text
orderby new { MemberName, GroupName }
select new
{
x.Member,
x.MemberGroup,
MemberName,
GroupName,
};

Is there a particular reason that this query is in this format?
Why are there not use of joins?
Need to really understand what you want here first and get into better sql before going to linq.

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 - count from select with join with no group by

Linq is brand new to me so I apologize if this is really stupid.
I am trying to get the count from a multi-table join with where clause, without group by. I've seen examples of group by and will resort to that if need be, but I am wondering if there is a way to avoid it. Is sql my query would look something like this;
SELECT Count(*)
FROM plans p
JOIN organizations o
ON p.org_id = o.org_id
AND o.deleted IS NULL
JOIN orgdata od
ON od.org_id = o.org_id
AND od.active = 1
JOIN orgsys os
ON os.sys_id = od.sys_id
AND os.deleted IS NULL
WHERE p.deleted IS NULL
AND os.name NOT IN ( 'xxxx', 'yyyy', 'zzzz' )
What's the best way to get this?
All you need is to call Count(). You're only counting the number of results. So something like:
var names = new[] { "xxxx", "yyyy", "zzzz" };
var query = from plan in db.Plans
where plan.Deleted == null
join organization in db.Organizations
on plan.OrganizationId equals organization.OrganizationId
where organization.Deleted == null
join orgData in db.OrganizationData
on organization.OrganizationId equals orgData.OrganizationId
where orgData.Active == 1
join os on db.OrganizationSystems
on orgData.SystemId equals os.SystemId
where os.Deleted == null &&
!names.Contains(os.Name)
select 1; // It doesn't matter what you select here
var count = query.Count();

MVC3 select int value through LINQ

I am trying to get customerId from Customer table.
However, when I try to make it, it has error said, 'Cannot implicitly convert type 'System.Linq.Iqueryable' to 'int''
How can I get customerId??
Thank you.
Here is my coding.
int customerId = from a in db.Customer
where a.userName == customerName
select a.customerId;
//it has error in here.
order.customerId = customerId;
It's possible that your query could return multiple rows. You need to tell LINQ that you only want the first (or a single) result:
int customerId = (from a in db.Customer
where a.userName == customerName
select a.customerId).First();
I like using the .Single() function when I know there should be only one row.
int customerId = (from a in db.Customer
where a.userName == customerName
select a.customerId).Single();
This throws an exception if more or less than one row is found, which is sometimes useful depending on your situation.
use it this way:
var customer = db.Customer.FirstOrDefault(c =>c.userName == customerName)
var id = customer.Id
Select returns an IEnumerable, so you can't convert it to int.
There is one more suggestion I can recommend for this question is to use First or default.
var customerId = (from a in db.Customer
where a.userName == customerName
select a.customerId).FirstOrDefault();
order.customerId = customerId; this should now work fine since it already knows it int

Convert SQL query to LINQ

The below is my SQL query and want to be in LINQ. Can anybody help for this?
SELECT EmpId,Team,_Year FROM Plan
where EmpId in
(
select EmpId from master where 2150 in (immediatesupervisor,manager)
)
I suggest you to use join operation like this
YourDbEntities db = new YourDbEntities();
var query = from c in db.Plan
join d in db.master on c.EmpId equals d.EmpId
where d.ImmediateSupervisor == 2150 || d.Manager == 2150
select new{
c.EmpId,
c.Team,
c._Year
};
Try:
var q =
from p in dc.Plan
where (
from m in dc.Master
where m.ImmediateSupervisor == 2150
|| m.Manager == 2150
select m.EmpId
).Contains(p.EmpId)
select new { p.EmpId, p.Team, p._Year };
A great resource for commonly used linq syntax is Damien Guard's Linq-to-SQL 'cheat sheet'. It is a one-pager where you can quickly look up things like this. See http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet

Entity Framework T-Sql "having" Equivalent

How can I write a linq to entities query that includes a having clause?
For example:
SELECT State.Name, Count(*) FROM State
INNER JOIN StateOwner ON State.StateID = StateOwner.StateID
GROUP BY State.StateID
HAVING Count(*) > 1
Any reason not to just use a where clause on the result?
var query = from state in states
join stateowner in stateowners
on state.stateid equals stateowner.stateid
group state.Name by state.stateid into grouped
where grouped.Count() > 1
select new { Name = grouped.Key, grouped.Count() };
I believe you can use a GroupBy followed by a Where clause and it will translate it as a Having. Not entirely sure though.
If you want to compare a variable that is not in the group by (Ex: age), then it would be:
var duplicated = (
from q1 in db.table1
where (q1.age >= 10 )
group q1 by new { q1.firstName, q1.lastName } into grp
where (grp.Count() > 1 )
select new
{
firstName= grp.Key.firstName,
lastName = grp.Key.lastName,
}
);

Resources