Linq Left Join selecting a collection as a property - c#

I'm new to Linq and I'm trying to join two table's - left join to be precise, I'm expecting top 10 results where the property of a result is a collection.
consider the sample model
Class A { int Id, List<B> Collection }
Class B { int Id, int x, int y }
I'm trying to perform left join such that the response I expect needs to be in the following format:
int A
Collection (part of B) =>{int x}
I tried with the following query
From A in _context.A
Join B in (from B in _context.B select new {Id, x }) on B.Id equals A.Id Into subB
From minimalB in subB.defaultIfEmpty()
Select {A.Id, minimalB.x}
How do i achieve the result such that the x property maps in as a collection to the result.
I Apologize for absurd explanation of the question in prior!

I don't think you need from minimalB in subB.defaultIfEmpty part, because it will create something similar to a cartesian product from your sets of data which represented as range variables (a and minimalB ). So to have a collection of X-s, you can try the following:
var query = from a in context.A
join b in context.B on a.Id equals b.Id into groupedB
where groupedB.Any()
select new { a.Id, Xs = groupedB.Select(b => b.X) };
By the way, if you already have the B collection in your A class, you can make the query without explicit joins (under the hood the query provider still will make join)
var query = _context.A.Select(a => new
{
a.Id,
Bs = a.Collection.Select(b => new { b.X, b.Y })
});

Related

Linq grouping - <k,v> where does my 'V' go?

In the following code:
var finalArticles =
from domainArticle in articlesFoundInDomain
join articleCategoryVersion in dbc.ArticlesCategoriesVersions
on domainArticle.ArticleID equals articleCategoryVersion.ArticleID
join articleCategory in dbc.ArticleCategories
on articleCategoryVersion.CategoryID equals articleCategory.CategoryID
where articleCategory.ParentID == 52
group articleCategory by articleCategory.CategoryID
into newArticleCategoryGroup
I understand that the group clause should be returning an IEnumerable where k is the Key, in this case CategoryID.
I think I'm misunderstanding Linq at this point because I assume that for each 'k' there should be a list of articles in 'v', but I don't understand the mechanisms or terminology or something. When I try to project this statement into a new anonymous object I don't seem to get any articles... where are they?
Edit:
Okay so I've got a piece of code that is working, but unfortunately it's hitting the SQL server multiple times:
var articlesAssociatedWithKnowledgeTypes =
from categories in dbc.ArticleCategories
join categoryVersions in dbc.ArticlesCategoriesVersions
on categories.CategoryID equals categoryVersions.CategoryID
join articles in articlesFoundInGivenDomain
on categoryVersions.ArticleID equals articles.ArticleID
where categories.ParentID == 52 && articles.Version == categoryVersions.Version
select new
{
ArticleID = articles.ArticleID,
ArticleTitle = articles.Title,
ArticleVersion = articles.Version,
CategoryID = categories.CategoryID,
CategoryName = categories.Name
} into knowledgeTypesFlat
group knowledgeTypesFlat by new { knowledgeTypesFlat.CategoryID, knowledgeTypesFlat.CategoryName } into knowledgeTypesNested
select new
{
CategoryID = knowledgeTypesNested.Key.CategoryID,
CategoryName = knowledgeTypesNested.Key.CategoryName,
Articles = knowledgeTypesNested.ToList()
};
I thought the ToList() on Articles would sort that out but it doesn't. But, the code works although I'm not sure if this is optimal?
The grouping returns an enumeration of IGroupings. IGrouping<K, V> itself implements IEnumerable<V>. Think of each group as an enumerable of all the members of that group plus an extra property Key
In your first query you are showing a group by and the second one is a group join, both return different results. The group by returns an IEnumerable<IGrouping<TKey, TElement>>. To get the result you're expecting you could group by CategoryId and CategoryName and project as I show below:
var finalArticles =
from domainArticle in articlesFoundInDomain
join articleCategoryVersion in dbc.ArticlesCategoriesVersions
on domainArticle.ArticleID equals articleCategoryVersion.ArticleID
join articleCategory in dbc.ArticleCategories
on articleCategoryVersion.CategoryID equals articleCategory.CategoryID
where articleCategory.ParentID == 52
group articleCategory by new{ articleCategory.CategoryID,articleCategory.CategoryName}
into g
select new {CatId=g.Key.CategoryID, CatName=g.Key.CategoryName,Articles =g.ToList() };
When you need the grouped elements you can call ToList or ToArray as I did above
Your finalArticles query results in a IEnumerable<IGrouping<int, Article>> (assuming CategoryID is int and your articles are of type Article).
These IGrouping<int, Article> provides a Key property of type int (your CategoryID and also the IEnumerable<Article> representing the sequence of articles for that CategoryID.
You can turn this for example into a Dictionary<int, List<Article>> mapping CategoryIDs to the lists of articles:
var dictionary = finalArticles.ToDictionary(group => group.Key, group => group.ToList());
or to a list of categories containing articles:
var categories = finalArticles.Select(group => new {
CategoryID = group.Key,
Articles = group.ToList()}).ToList();
Update after your comment:
var finalArticles =
from domainArticle in articlesFoundInDomain
join articleCategoryVersion in dbc.ArticlesCategoriesVersions
on domainArticle.ArticleID equals articleCategoryVersion.ArticleID
join articleCategory in dbc.ArticleCategories
on articleCategoryVersion.CategoryID equals articleCategory.CategoryID
where articleCategory.ParentID == 52
group articleCategory by new {articleCategory.CategoryID, articleCategory.Name}
into newArticleCategoryGroup
select new
{
CategoryID = newArticleCategoryGroup.Key.CategoryID,
CategoryName = newArticleCategoryGroup.Key.Name,
Articles = newArticleCateGroup.ToList()
}

MVC - Joining multiple table using LINQ / lambda - Using EF

I am implementing a controller and I need to get all staff members which have a certain RiskTypeID, which will be selected by the user when they click on Navigation Item.
Here is how I would create the joins in SQL
SQL
Select
RTHG.RiskTypeID,
SM.FullName
From RiskTypeHasGroup RTHG
Inner join RiskGroup RG On RTHG.RiskGroupID = RG.ID
Inner join RiskGroupHasGroupMembers RGHGM ON RG.ID = RGHGM.RiskGroupID
Inner Join GroupMember GM ON RGHGM.GroupMemberID = GM.ID
Inner Join GroupMemberHasStaffMember GMHSM ON GM.ID = GMHSM.GroupMemberID
Inner Join StaffMember SM ON GMHSM.StaffMemberID = SM.ID
Where RTHG.RiskTypeID = 1
I’ve pulled back data before using Linq and lambda but only using simple expressions, I now need to be able to make a call which will bring back the same data as the sql outlined above, I’ve searched online but can’t find anything similar to my requirement.
Here is my Controller, I placed comments inside as guidance
Controller
public ActionResult ViewRiskTypes(int SelectedRiskTypeID)
{
var RiskTypes = _DBContext.RiskTypes.ToList(); // Get all of the current items held in RiskTypes tables, store them as a List in Var RiskTypes
var ViewModel = new List<RiskTypeWithDetails>(); // Create colletion which holds instances of RiskTypeWithDetails and pass them to the ViewModel
var Details = new RiskTypeWithDetails(); // Create a new instance of RiskType with details and store the instance in var Details
foreach (var RiskType in RiskTypes) // Loop through each Item held in var RiskTypes
{
Details.RiskTypes.Add(new RiskTypesItem { ID = RiskType.ID, Description = RiskType.Description }); // assign each items ID & Description to the same feilds in a new
// instance of RiskTypeItems (which is a property of RiskTypeWithDetails)
}
foreach (var RiskType in RiskTypes) // Loop through each item in RiskTypes
{
if (RiskType.ID == SelectedRiskTypeID) // Check Item ID matches SelectedRiskTypeID value
{
//var Details = new RiskTypeWithDetails();
Details.RiskTypeDescription = RiskType.Description; //assign the Risk type Descripton to RiskTypeWithDetails RiskTypeDescription Property
Details.RiskDetails = _DBContext
.RiskTypeHasGroups
//.GroupMemberTypeHasGroupMembers
.Where(r => r.RiskTypeID == SelectedRiskTypeID) // Where RiskTypeId matches Selected ID bring back following data from Db
.Select(r => new RiskDetails
{
RiskGroupDescription = r.RiskGroup.Description,
GroupMembers = r.RiskGroup.RiskGroupHasGroupMembers
.Select(v => v.GroupMember).ToList(),
//StaffMembers = r.RiskGroup.RiskTypeHasGroups
// .Join(r.RiskGroup.RiskTypeHasGroups,
// a => a.RiskGroupID , b => b.RiskGroup.ID,
// (a, b) => new {a, b})
// .Join(r.RiskGroup.RiskGroupHasGroupMembers,
// c => c.) // Dosent join as I would expect... no idea what to do here
}).ToList();
ViewModel.Add(Details); //Add all data retrieved to the ViewModel (This creates one item in the collection)
}
}
return View(ViewModel);
}
As you will see I want to get all Staff Members with a match for the selected RiskTypeID. I need some assistance in converting the above SQL to work within my controller as a lambda expression
Thanks in advance
You were on the right track with your commented out code! For starters, LINQ has two different sytaxes: query and method chain. You were using the method chain syntax and it can get really unmaintainable really quickly.
For an instance like this, query syntax is where it's at.
Here's the result:
from rhtg in _dbContext.RiskTypeHasGroup
where rhtg.RiskTypeID == 1
join rg in _dbContext.RiskGroup
on rhtg.RiskGroupID equals rg.ID
join rghgm in _dbContext.RiskGroupHasGroupMembers
on rg.ID equals rhtg.ID
join gm in _dbContext.GroupMember
on rg.ID equals gm.ID
join gmhsm in _dbContext.GroupMemberHasStaffMember
on gm.ID equals gmhsm.GroupMemberID
join sm in _dbContext.StaffMember
on gmhsm.StaffMemberID equals sm.ID
select new
{
rhtg.RiskTypeId,
sm.FullName
};
Do note, that I used .Net conventions for the different variables.
Here's some documentation on the query syntax:
https://msdn.microsoft.com/en-us/library/gg509017.aspx
You can write the exact same query in linq as follows:
var query = (from RTHG in _DBContext.RiskTypeHasGroup RTHG
join RG in _DBContext.RiskGroup on RTHG.RiskGroupID equals RG.ID
join RGHGM in _DBContext.RiskGroupHasGroupMembers on RG.ID equals RGHGM.RiskGroupID
join GM in _DBContext.GroupMember on RGHGM.GroupMemberID = GM.ID
join GMHSM in _DBContext.GroupMemberHasStaffMember on GM.ID equals GMHSM.GroupMemberID
join SM in _DBContext.StaffMember on GMHSM.StaffMemberID equals SM.ID
where RTHG.RiskTypeID == 1
select new {RTHG.RiskTypeID,SM.FullName});

"cannot implicitly convert .." when using LINQ Where

I'm trying to write a query in a c# program that gets all items out of a database where a particular id in that item is contained in a list I have. I also need to join on a few tables..
What I have is:
var data = from a in db.Apples.Where(a => myApples.contains(a.type))
from b in db.Banans where b.Id = a.bananaPair.Id
from c in db.Coconuts where c.Id = c.coconutPair.Id
select new {
apple = a,
bananaName = b.name,
coconutName = c.name,
});
I get an error on "where b.Id = a.bananaPair.Id" that "cannot implicitly convert int to bool". I think I am mixing types.. the first where is a comparison, and the others is a join condition. How can I do both in the query? I need pieces of information from all 3 tables in my select object.
Thanks
Change it to
var data = from a in db.Apples.Where(a => myApples.contains(a.type))
from b in db.Banans where b.Id == a.bananaPair.Id
from c in db.Coconuts where c.Id == c.coconutPair.Id
select new {
apple = a,
bananaName = b.name,
coconutName = c.name,
});
You had b.Id = a.bananaPair.Id. That assigns a.bananaPair.Id to b.Id. The reason your error was calling this assignment an int is because assignments return the value assigned. You want b.Id == a.bananaPair.Id, which tests whether they're equal.
As commenter #misterManager suggests, you could also use join here. Let me know if this doesn't work, though, it's been so long since I've used query syntax.
var data = from a in db.Apples.Where(a => myApples.contains(a.type))
join b in db.Bananas on a.bananaPair.Id equals b.Id
join c in db.Coconuts on c.coconutPair.Id equals c.Id
select new {
apple = a,
bananaName = b.name,
coconutName = c.name,
});
By the way, I couldn't help but notice your c line: from c in db.Coconuts where c.Id == c.coconutPair.Id, should that be a.coconutPair.Id?

LINQ using dictionary in where clause

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.

LinqProvider that gets data from from two places and merges them

I have a Linq query that looks something like the following
var query3 = from c in Session.CreateLinq<AccountTransaction>()
join a in Session.CreateLinq<Account>() on c.Account equals a
where c.DebitAmount >= 0
select new { a.Name, c.DebitAmount }
;
The Session object interacts with a datasource behind the scenes but it also has an internal cached state which may have changes. When I run a query I would like to query the both the internal cached state AND the datasource and then merge the results together, with the internal cached state taking precendence.
I am using re-linq for the generation of the query against the datasource which is working fine. What I am not sure about is how to also do the query against the internal state using the same Linq query.
There's a call GetAllCached() on Session that I can use instead of Session.CreateLinq if I just wanted to query the internal state. But I'm not sure at which point in my custom provider I can handle handing off to the datasource AND the internal state using GetAllCached().
Any suggestions appreciated from any Linq gurus.
// From Database
var query1 = from c in Session.CreateLinq<AcccountTransaction>()
join a in Session.CreateLinq<Account>()
on c.Account equals a
where c.DebitAmount >= 0
select new { Account = a, AccountTrans = c };
//select new { a.Name, c.DebitAmount };
// From Cache
var query2 = from c in Session.GetAllCached<AcccountTransaction>()
join a in Session.GetAllCached<Account>()
on c.Account equals a
where c.DebitAmount >= 0
select new { Account = a, AccountTrans = c };
//select new { a.Name, c.DebitAmount };
//var query3 = query2.Union(query1.Except(query2));
var query4 = query2.Union(query1);
Modified: 04:51 AM Singapore Time
If I understand correctly, you have a single custom LINQ provider for your datasource, and a (presumably type-safe) way of getting cached results as well.
In this case, I recommend just using LINQ to Objects to access your cached set. You can use AsEnumerable to "step out" of your custom LINQ provider into LINQ to Objects.
The join brings up a problem, though. Since either of these types may exist in the cache, it's not possible to push logic to the DB. For example, is it possible to have an AccountTransaction in the cache without its Account also being in the cache?
If you allow any situation in the cache (e.g., AccountTransaction without associated Account records), then you have to do the join in memory and not in the db:
var allDebitAccountTransactions = Session.GetAllCached<AccountTransaction>()
.Where(x => x.DebitAmount >= 0)
.Union(Session.CreateLinq<AccountTransaction>()
.Where(x => x.DebitAmount >= 0));
var allAccounts = Session.GetAllCached<Account>()
.Union(Session.CreateLinq<Account>());
var query3 = from c in allDebitAccountTransactions
join a in allAccounts where c.Account equals a
select new { a.Name, c.DebitAmount };
However, if you have more control over your cache, and only allow AccountTransaction objects to be present if their associated Account objects are present, then you can push the join operation to the datasource and do another one in memory, merging the results:
var datasourceResults = from c in Session.CreateLinq<AccountTransaction>()
join a in Session.CreateLinq<Account>() on c.Account equals a
where c.DebitAmount >= 0
select new { a.Name, c.DebitAmount, c.Id };
var cacheResults = from c in Session.GetAllCached<AccountTransaction>()
join a in Session.GetAllCached<Account>() on c.Account equals a
where c.DebitAmount >= 0
select new { a.Name, c.DebitAmount, c.Id };
var query3 = cacheResults.Union(datasourceResults)
.Select(x => new { x.Name, x.DebitAmount });
I think. I am not an expert in LINQ, so I'm curious to see other responses.

Categories