Posts

Showing posts with the label Entity Framework

LINQ: Using int.TryParse() within a LINQ where clause

I pretty new to LINQ, and I’m keen to get more experience using it, so whenever an opportunity arises I like to try writing LINQ queries. I needed to write a method to extract a comma separated list of numbers from a config file, and return this as List. I was looking at ways to do this using LINQ, but hit a problem. I wanted my LINQ query to filter out any values in the CSV string that could not be parsed as an int, without causing an exception. Using int.TryParse() seemed like a possible solution, but I had problems because the TryParse() method has an out parameter to store the parsed result. I ended up with the code below, which seems to work, but looks very messy, because I think it is parsing the string twice. public static List<int> AuthorisedGroups { get       {             string[] authorisedGroupsStr = ConfigurationManager.AppSettings["AuthorisedGroups"].Split(new char[] { ...

LINQ: Implement NOT IN tables with LINQ to Entity

In SQL so many times we need to filter value from one table when the values are not exist on other table. As Below SELECT    GroupID ,    GroupName ,    GroupNumber      FROM  TableA     WHERE  GroupID NOT IN ( SELECT GroupID FROM TableB )   You can do it as below: return   from c in  context . TableA where !db. context . TableB .Any(p => p.GroupID== c.GroupID) select c;

LINQ: implement IN tables with LINQ to Entity

In SQL so many times we need to filter value from one table when the values are exist on other table. As Below SELECT    GroupID ,    GroupName ,    GroupNumber ,   FROM    TableA  WHERE    GroupID IN ( SELECT GroupID FROM TableB )   You can do it as below:  var temp = context . TableA           . Where ( x => context . TableB . Any ( y => y . GroupID != x . GroupID ))           . Select ( x => new { GroupID = x . GroupID , GroupName = x . GroupName , GroupNumber = x . GroupNumber }). ToList (); or return DomainContext.TableA.Where(a => DomainContext.TableB.Any(b => b.GroupId == a.GroupId))

LINQ: Left Outer Join With LINQ to Entity

In LINQ every join you made is by default Inner Join. To perform the Left Outer Join you can do like below: from mem in ctx.Member join dist in ctx.District on mem.district_id equals dist.district_id into jointDist from dist in jointDist.DefaultIfEmpty() select new StagingClass {  member_id = mem.member_id,  district_name = dist.district_name }

LINQ: Showing Single Record From Child Table with Parent Table Row.

In LINQ if you want to show the child table single record with the parent table, you can do like below: from mem in ctx.Member join ord in ctx.MemOrder on mem.member_id equals ord.member_id into memord select new StagingClass {  mem.member_id,  latestOrderNo = memord.FirstOrDefault().OrderNo }