linq with Include and many-to-many - linq

I have rather specific requirement for my Linq statement. I've looked through dozens of examples, but could't find satisfying answer.
I have a collection of courses, which holds collection of groups, which holds collection of members. My goal is to create linq statement for IQuerable which returns a collection of courses that user belongs to, and includes collection of groups within each course that user belongs to if there is any.
I did manage to build a linq statement which returns what I wanted but filters out all of the courses that don't have any groups that user belongs to inside them:
var courses2 = (from c in _set
from s in c.Students
where (s.UserName == userName)
from g in c.Groups
from m in g.Members
where (m.UserName == userName)
select c)
.Include(c => c.Groups)
.OrderBy(c => c.Title)
How could I change it to include those as well?

Assuming your student entity has a nav property to entity Class for class membership, and Class entities have a nav property Groups to the Group entity, which in turn have a nav property to Students:
// get the students to query against
var students = db.Students.Where( s => s.UserName == userName );
// get classes per group
var classesViaGroups =
students.SelectMany( s => s.Groups )
.SelectMany( g =>
g.Classes.Select( c =>
new { GroupName = g.Name, ClassObj = g.Class } ) );
// get classes by the student entities alone
var classesViaStudents =
students.SelectMany( s => s.Classes )
.Select( c => new { GroupName = null, ClassObj = c } );
You can then do what you will with classesViaGroups and classesViaStudents - combine them, build a lookup or dictionary by group or class, etc.

Related

How to order items within the group of anonymous type?

I would like to get a result of Linq query as groups of anonymous objects. The items within the groups should be ordered by ID field. I can reach this partly by lambda syntax, but can't get an anonymous objects as result. So I need part of each example.
Executable code: https://dotnetfiddle.net/cPJUN9
var res_g = (from dg in list
group new { dg.ID, dg.IDOperation, dg.IDDiagnosis } by dg.IDOperation
into dg_group
select dg_group);
lambda syntax
var res_g = list
.GroupBy(x => x.IDOperation)
.Select(x => x.OrderBy(x => x.ID)); // order dg by ID asc within group
Alas, you didn't describe exactly your requirements where, only that you want some anonymous type and that they should be ordered by Id. Your query syntax makes different groups than your method syntax. So I can only give an example to create your sequence of anonymous objects
So you have a sequence of similar items, where every item has at least properties Id and IdOperation. You want to make groups of items where every item in each group has the same value for IdOperation. You want to order the elements in each group by ascending Id, and create some anonymous type.
You didn't specify what you want in your anonymous object (after all: your code doesn't do what you want, so I can't deduct it from your code)
Whenever I use GroupBy, and I want to specify the elements of each group, I use the overload of GroupBy that has a parameter resultSelector. With the resultSelector I can precisely define the elements of the group. (The link refers to IQueryable, there is also an IEnumerable version)
IEnumerable<Operations> operations = ... // = your list
// Make Groups of Operations that have the same value for IdOperation
var result = operations.GroupBy(operation => operation.IdOperation,
// parameter resultSelector: take the key (=idOperation) and all Operations that have
// this idOperation, to make one new.
(idOperation, operationsWithThisId) => new
{
// do you need the common idOperation?
IdOperation = idOperation,
// Order the elements in each group by Id:
Operations = operationsWithThisId.OrderBy(operation => operation.Id)
.Select(operation => new
{
// Select only the operation properties that you plan to use
Id = operation.Id,
Name = operation.Name,
StartDate = operation.StartDate,
...
})
.ToList(),
});
In words: from your sequence of Operations, make groups of Operations that have the same value for IdOperation. Then take this common IdOperation, and all Operations that are in this group, to make one anonymous object: this is the anonymous object that you were talking about. So per group, you make one anonymous object.
IdOperation is the value that all Operations in this group have in common
Operations is a list. All Operations in this group are ordered by ascending Id. Several properties are Selected and the result is put in a List.
If you want to group differently, like in you query syntax, simply change parameter keySelector:
var result = operations.GroupBy(operation => new
{
Id = operation.ID,
IdOperation = operation.IDOperation,
IdDiagnosis = operation.IDDiagnosis
},
Although this corresponds with what you did in your query syntax, you will have groups of Operations that have same value for Id / IdOperation / IDDiagnosis. It will be useless to sort the elements in the group by Id, because all Ids in this group will be equal.
Conclusion
With parameter resultSelector you can define the result exactly as you want: the result is not an IEnumerable<IGrouping<Tkey, TElement>>, but an IEnumerable<TResult>.
The TResult is one object created from all elements in one group and the common group value.
you can update GetDict function inner loop to use orderby on group elements
public static void GetDict(List<Operation> list)
{
var res_g = (from dg in list
group new { dg.ID, dg.IDOperation, dg.IDDiagnosis } by dg.IDOperation
into dg_group
select dg_group);
foreach (var x in res_g)
{
Console.WriteLine("Key: " + x.Key);
foreach (var y in x.OrderBy(o=>o.ID))
{
Console.WriteLine("{0} {1} {2}", y.ID, y.IDOperation, y.IDDiagnosis); ;
}
}
}
I hope this solve the issue.
Depending on your Requirements EDIT but I'm Tuning the result set
var res_g_2 = list.Select( p=> new { p.ID, p.IDOperation, p.IDDiagnosis }) .GroupBy(g => g.IDOperation)
.Select(g => new {
IDOperation = g.Key,
Records = g.OrderBy(group => group.ID)
});
Edit full version
public static void GetDict(List<Operation> list)
{
var res_g = (from dg in list
group new { dg.ID, dg.IDOperation, dg.IDDiagnosis } by dg.IDOperation
into dg_group
select new
{
Key = dg_group.Key,
Records = dg_group.OrderBy(g => g.ID)
}) ;
var res_g_2 = list.Select( p=> new { p.ID, p.IDOperation, p.IDDiagnosis }) .GroupBy(g => g.IDOperation)
.Select(g => new {
Key = g.Key,
Records = g.OrderBy(group => group.ID)
});
// you can use either res_g or res_g_2 both give the same results
foreach (var x in res_g)
{
Console.WriteLine("Key: " + x.Key);
foreach (var y in x.Records)
{
Console.WriteLine("{0} {1} {2}", y.ID, y.IDOperation, y.IDDiagnosis); ;
}
}
}

get list from a class to fill taxtbox in other class by linq

how to get just special 2 attributes from a table to other table( and placement in related textbox) by LINQ??
public string srcht(ACTIVITIES sn)
{
db db = new db();
var q = (from i in db.costumers.Where(i => i.id== sn.id)select i.name).ToList();
return q.Single();
}
public string srcht(ACTIVITIES sn)
{
db db = new db();
var q = (from i in db.costumers.Where(i => i.id== sn.id)select i.family).ToList();
return q.Single();
}
i did linq twice to fill 2 textboxes by name and family in other table. can i do it by one LINQ?
So you have an Activity in sn, and you want the Name and the Family of all Customers that have an Id equal to sn.Id.
var result = db.Customers.Where(customer => customer.Id == sn.Id)
.Select(customer => new
{
Name = customer.Name,
Family = customer.Family,
});
In words: in the database, from the table of Customers, keep only those Customers that have a value for property Id that equals the value of sn.Id. From the remaining Customers select the values of Name and Family.
If you expect that there will only be at utmost one such customer (so if Id is the primary key), just add:
.FirstOrDefault();
If you think there will be several of these customers, add:
.ToList();
The result will be an object, or a list of objects of some anonymous type with two properties: Name and Family.
If you want to mix the Name and the Family in one sequence of strings, which I doubt, consider to put the Name and the Family in an array. Result is sequence of arrays of strings. To make it one array of Strings, use SelectMany:
var result = db.Customers
.Where(customer => customer.Id == sn.Id)
.Select(customer => new string[]
{
customer.Name,
customer.Family,
})
.SelectMany(customer => customer);

MVC many to many get entities with of certain type only in code first

I have a many to many relationship between Company and CompanyType
I want to get a list for a dropdown of only Companies with a CompanyType.Name of "Client". I.e. a clientCompanyList.
How can I do that in linq?
I basically wanted to do the following but in linq
var clientCompanies = db.Companies.SqlQuery(#"SELECT c.*
FROM Companies AS c
JOIN CompanyTypeCompanies AS ctc ON ctc.Company_ID = c.ID
JOIN CompanyTypes AS ct ON ctc.CompanyType_ID = ct.ID
WHERE ct.Name = 'Client'").ToList();
You can use include statement, if it having proper foreign key relation ships between tables
var clientCompanies = db.CompanyTypes
.Where(ct => ct.Name == "Client").Include(ct => ct.CompanyTypeCompanies).Include(ct => ct.Companies).Select(ct => ct.Companies).ToList();
In startup class
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}

Projections over sub collections - EF4

Lets assume the following model with EF4:
class Order
{
....
public int Id {get;private set;}
//ICollection is the root of all evil here
public ICollection<OrderDetail> Details {get;private set;}
}
I can then project over this structure with Linq:
var IdAndCount = context
.Orders
.Select ( o => new {
Id = o.Id,
Count = o.Details.Where(d => d.Foo > 0).Count()});
So far so good, this will be fully translated to sql.
Now to the problem, what if I want to extract the where clause predicate in this query:
Func<OrderDetail,bool> detailPredicate = d => d.Foo > 0;
var IdAndCount = context
.Orders
.Select ( o => new {
Id = o.Id,
Count = o.Details
.Where(detailPredicate)
.Count()});
This compiles, but fails at runtime because there is no way for EF4 to translate the predicate to SQL since it is a Func and not an Expression.
Changing the predicate to an Expression<Func<OrderDetail,bool>> will not work since ".Where" on the OrderDetails links to the IEnumerable "Where" since the details are ICollection.
So, is it possible to extract parts of a bigger Linq query if the properties beeing traversed are IEnumerable or similair?
Try
Expression<Func<OrderDetail,bool>> detailPredicate = d => d.Foo > 0;

Linq To Entities - how to filter on child entities

I have entities Group and User.
the Group entity has Users property which is a list of Users.
User has a property named IsEnabled.
I want to write a linq query that returns a list of Groups, which only consists of Users whose IsEnabled is true.
so for example, for data like below
AllGroups
Group A
User 1 (IsEnabled = true)
User 2 (IsEnabled = true)
User 3 (IsEnabled = false)
Group B
User 4 (IsEnabled = true)
User 5 (IsEnabled = false)
User 6 (IsEnabled = false)
I want to get
FilteredGroups
Group A
User 1 (IsEnabled = true)
User 2 (IsEnabled = true)
Group B
User 4 (IsEnabled = true)
I tried the following query, but Visual Studio tells me that
[Property or indexer 'Users' cannot be assigned to -- it is read only]
FilteredGroups = AllGroups.Select(g => new Group()
{
ID = g.ID,
Name = g.Name,
...
Users = g.Users.Where(u => u.IsInactive == false)
});
thank you for your help!
There is no "nice" way of doing this, but you could try this - project both, Group and filtered Users onto an anonymous object, and then Select just the Groups:
var resultObjectList = AllGroups.
Select(g => new
{
GroupItem = g,
UserItems = g.Users.Where(u => !u.IsInactive)
}).ToList();
FilteredGroups = resultObjectList.Select(i => i.GroupItem).ToList();
This isn't a documented feature and has to do with the way EF constructs SQL queries - in this case it should filter out the child collection, so your FilteredGroups list will only contain active users.
If this works, you can try merging the code:
FilteredGroups = AllGroups.
Select(g => new
{
GroupItem = g,
UserItems = g.Users.Where(u => !u.IsInactive)
}).
Select(r => r.GroupItem).
ToList();
(This is untested and the outcome depends on how EF will process the second Select, so it would be nice if you let us know which method works after you've tried it).
I managed to do this by turning the query upside down:
var users = (from user in Users.Include("Group")
where user.IsEnabled
select user).ToList().AsQueryable()
from (user in users
select user.Group).Distinct()
By using the ToList() you force a roundtrip to the database which is required because otherwise the deferred execution comes in the way. The second query only re-orders the retrieved data.
Note: You might not be able to udpate your entities afterwards!
try something like this and you'll still have your entities:
FilteredGroups = AllGroups.Select(g => new
{
Group = g,
Users = g.Users.Where(u => u.IsInactive == false)
}).AsEnumerable().Select(i => i.Group);
That way you should still be able to use Group.Users
If you want to retain your entity structure, try this:
var userGroups = context.Users.Where(u => !u.IsInactive).GroupBy(u => u.Group);
foreach (var userGroup in userGroups)
{
// Do group stuff, e.g.:
foreach (var user in userGroup)
{
}
}
And you certainly can modify your entities!
Use inner linq query
var FilteredGroups = (from g in AllGroups
select new Group()
{
ID = g.ID,
Name = g.Name,
...
Users = (from user in g.Users
where user.IsInactive == false
select user).ToList()
});

Resources