display it into the "Table1" table - c#

Here are the methods mentioned above:
public IList<tst> testUsers()
{
IList<tst> testUsers = _test.GetAll().ToList();
return test(test);
}

To display Users with Location I think you need one class called AdsnapshotUsers
public class AdsnapshotUsers
{
// three fields UserId, UserLogonName, Location
}
Now create one method which return IList<AdsnapshotUsers>
public IList<AdsnapshotUsers> GetAdsnapshotUsers()
{
List<User> Users = GetAcitveUsers().ToList();
List<ADSnapshot> adSnapshotUsers = _adSnapshotRepository.GetAll().ToList();
return (from u in Users
join ad in adSnapshotUsers on u.UserLogonName equals ad.UserLogonName
select new AdsnapshotUsers {
UserId= u.UserId, UserLogonName = u.UserLogonName, Location = ad.Location
}
).ToList<AdsnapshotUsers>();
}
Left Outer Join to display all the values from the user table eventhough if a userlogonname is not present in the adsnapshot table (location value blank)
(from u in Users
join ad in adSnapshotUsers on u.UserLogonName equals ad.UserLogonName into aduserselect
from ad1 in aduserselect.DefaultIfEmpty()
select new AdsnapshotUsers {
UserId= u.UserId, UserLogonName = u.UserLogonName, Location = ad1.Location
}
).ToList<AdsnapshotUsers>();
Here all records from user table will get selected and for location if userlogonname exist then location name value set with ADSnapshot table value otherwise not exist then default empty value set.

The simplest way to join two IEnumerables in LINQ is with Join():
var joined = from u in GetActiveUsers()
join ad in _adSnapshotRepository.GetAll()
on u.UserLogonName equals ad.UserLogonName
select new { User = u, Location = ad.Location }
Of course, joined is now an IEnumerable of an anonymous type. If you are displaying this information in a grid view or something that requires a flat object, you may want to create your own class with the properties you want from each table and select that instead.
Two other things to note:
(1) you always seem to call ToList() early to convert from IQueryable to IEnumerable. By putting off ToList() until you've done all your joining and filtering, you can get most of your query to happen in SQL (rather than in memory).
(2) rather than joining, it is often preferable to set up associtation properties on your entities and use those:
IQueryable<User> users = ...
var combinedInfo = users.Select(u => new { User = u, Location = u.ADSnapshot.Location })
.ToList();

If you have relationship (1:1) between these two tables then you can get records very easily using just one query. and evenif records are not present in second table.
I am using above defined class definition to store data.
_userRepository.GetAll().Select(u=>new AdsnapshotUsers {
UserId= u.UserId,
UserLogonName = u.UserLogonName,
Location = u.ADSnapshot.Location
}).ToList();

Related

Can't select properties after group by in linq query

I have two tables, Organization and ApplicationUser. The relationship between them is One to Many. That means one Organization can have multiple Users. Now I need to write a query to show some organization properties along with the total users for each organization. I am trying to write the query. But after GroupBy function whenever I try to fetch the Property nothing comes. Here is the query:
var lists = await (from org in _dbContext.Organizations.AsNoTracking()
join dept in _dbContext.Departments.AsNoTracking() on org.Id equals dept.OrganizationId into orgDeptTemp
from orgDept in orgDeptTemp.DefaultIfEmpty()
join user in _dbContext.ApplicationUsers.AsNoTracking() on org.Id equals user.OrganizationId into orgUserTemp
from orgUser in orgUserTemp.DefaultIfEmpty()
group org by org.Id into orgGroupTemp
select new OrganizationDto
{
OrganizationId = orgGroupTemp.Key,
OrganizationName = orgGroupTemp.Key.......,
TotalUsers = How to get the total user
})
.ToListAsync();
In SQL the only available columns after a GROUP BY are the group key and aggregated columns.
You need to add them into the group by line. So for example, group by org id and name
assuming your model is set up correctly use navigation properties
var query = from org in _dbContext.Organizations
where org.Departments.Any(d => d.Whatever)
select new OrganizationDto
{
OrganizationId = org.Id,
OrganizationName = org.Name,
TotalUsers = org.Users.Count(),
};
var list = await query.AsNoTracking().ToListAsync();

How to get two table value using Linq

I have two table one is Administrator table and another is Teacher table .
I want to display these both tables values in single Gridview .
I have make id as a primary key in Administrator table and make this tech_id as foreign key in Teacher table .
Now how to get these table values together in single gridview as shown in pic
Now please any body help me how to get these two value together using Linq .
I have try but I can't make any more
private void loadgri()
{
StudentDatabaseEntities empl = new StudentDatabaseEntities();
var query=from g in empl.Teachers
join m in empl.Administrators on g.id equals m.id
where m.username=="cs"
select new{
Name = g.username,
};
}
You don't need a join if you have already a navigation-property:
var query= from t in empl.Teachers
where t.Administrator.username == "cs"
select new { Teacher = t.username, Administrator = t.Administrator.username };
This is just an example, but you see that you can access all properties of both entities.
Don’t use Linq’s Join. Navigate!
To show all the teachers and their administrator, you don't have to use "join", you could just use the navigation property:
var query = from g in empl.Teachers
where g.Administrator.username=="cs"
select new {
Teacher_Id = g.Id,
Teacher_Name = g.username,
Administrator_Id = g.Id,
Administrator_Name = g.Administrator.username,
//etc...
};

Include unrelated table in Linq to entity query

I have the following simplified setup:
Public User
{
//Primary key
public int Id {get;set;}
public string Name {get; set;}
}
Public UserInfo
{
//Primary key
public int Id {get;set;}
//Foreign key to user table
public int userKey {get; set;}
}
The relationship between the tables is one user to Many userInfo
I am trying to select from the user table and include the userInfo table.
I cannot do this:
var users = Context.user.Include(u => u.userInfos);
as there is no reference to the UserInfo table from the user table.
I can do this:
context.userInfo.include(x => x.user)
but if there are no corresponding entries in the userInfo table, this will not return any results, which is not what I want. Also, this will return one row for each userInfo, whereas I want one row for user, with a list of userInfo as a parameter.
Similarly I could join the tables like this:
var users = from us in Context.user
join inf in Context.userInfo
on us.Id equals inf.userKey
select new //etc
But this will also return one row per userInfo entry, the same problem as above.
To summarise, is there a way of including this table to produce a result in the same way as the include function does.
I know I could adjust my setup to all me to include this, but that is not what I am asking here.
I suspect this cannot be done, but from all my googling so far I have not been able to find a definitive answer....
I want one row for user, with a list of userInfo as a parameter
I assume you mean a list of userInfo as a property. My understanding of what you ask it that you're just looking for:
var users = from us in Context.user
join inf in Context.userInfo
on us.Id equals inf.userKey into infg
select new
{
User = us,
UserInfos = infg
};
join ... into amounts to a GroupJoin, i.e. a user entity joined with a group of userinfos.
Better still is to use a navigation property user.userInfos (reluctantly following your naming convention):
var users = Context.user.Include(u => u.userInfos);

From SQL server, extract a list of Users containing the list of all their bought application (mapping table)

Let Users be a database containing typical users data (name, email...) with an ID as primary key.
Let Applications be a database storing a list of applications (name, developer...) with an ID as primary key.
Let UsersApps be the mapping table between the two, using the primary key. UsersApps thus stores rows of ..., {102, user1_Id, appA_Id}, {103, userN_ID, appB_Id}, {104, user1_Id, appC_Id}, ...
And so on.
I want to retrieve a list of users data {name, email, List<Application> boughtApps}
I am struggling to find a LINQ request to do that and I am trying to do it in two steps, get a big table and then build each user's list of applications.
var q1 = from user in _dbContext.Users
join appUti in _dbContext.AppUsers on user.Id equals appUti.UsersId
join app in _dbContext.Applications on appUti.ApplicationId equals app.Id
orderby user.Id
select new UserDataWithApp { Id = user.Id, Name = user.Name, firstName= user.FirstName, Email = user.Email, App = app };
Then parse q1.toList() to build my required results list.
var qRes = q1.ToList();
int i = 0;
int j = 0;
while (i<qRes.Count())
{
listUsersWithApps[j] = qRes[i];
while (qRes[i].Id == listUsersWithApps[j].Id) // llist is ordered !!
{
listUsersWithApps[j].Apps.Add(qRes[i].Apps[0]);
i++;
}
j++;
}
Isn't there a better way ?
You can use navigation properties to allow the following:
var userApps = context.Users.Select(u => new UserWithApp(u.Name, u.Email, u.Applications))
Just add to following to User:
public virtual ICollection<Application> Applications { get; set; }
and to Application:
public virtual ICollection<Users> Users { get; set; }
So you can "navigate" between your entities and write to following query (just adapt your ordering and what user data to be seleted):
var userApps = from user in context.Users
select new UserDataWithApp { ..., BoughtApps = user.Applications }
See here for an example: http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
or another interesting blog: https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/

How to write a LINQ query to select from a collection with given set of matching IDs

I'm using a self tracking entity model. ProductInstallation is a DTO which contains all the details about the product installation for a company.
The UserRoles entity holds the relationship in-between the Product-System Role-UserID.
As an example:
Product: Inventory
System Role : PurchasingUser
User ID : hasithaH <- (Suppose me)
using the below LINQ query, I can get the distinct UserIDs.
string[] userIDs = productInstallation.UserRoles
.Select(u=>u.UserID).Distinct().ToArray();
now I need to get all the User Profiles for the UserIDs I queried in above steps.
productInstallation.SystemUsers = context.SystemUsers.Select(u=> u.UserID ..???
In SQL point of view, this is the query I want:
Select * from SystemUsers where UserID in ('UserA','UserB','UserC')
How should I write a LINQ query to get this done?
You write it as follows:
var result = context.SystemUsers.Where(su =>
productInstallation.UserRoles.Any(ur => su.UserID == ur.UserId));
Or if both sources are not IQuerable from the same db:
string[] userIDs = productInstallation.UserRoles
.Select(u=>u.UserID).Distinct().ToArray();
var result = context.SystemUsers.Where(su =>
userIDs.Contains(su.UserID));
What you really want to do here is join the two tables. Using a Join you can do this in one query rather than executing two separate queries:
var systemUsers = from userRole in UserRoles
join systemUser in SystemUsers
on userRole.UserID equals systemUser.UserID
select systemUser;
You can try this:
productInstallation.SystemUsers =
context.SystemUsers.FindAll(u=> userIDs.Contains(u.UserID))

Categories