Is it possible to use two context entities from two different database - c#

Is it possible to use two context entities from two different database
Code connectiong to one entity:
Using one FoodSupplyEntities
using (var contextFood = new FoodSupplyEntities())
{
var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
join _FoodQualityStatus in contextFood.FoodQualityStatus
But is it possible to join for example another table from a different entities from another server.?
Sample (Dont know but it might gosomething like this.)
using (var contextFood = new FoodSupplyEntities() and contextKitchenware = new KitchenwareEntities() )
{
var _result = (from _FoodSupplyStatus in contextFood.FoodSupplyStatus
join _KitchenwareSupplyStatus in contextKitchenware.KitchenwareSupplyStatus

Suppose you have 2 tables in 2 different databases:
User in Database1
Orders in Database2 where UserId of User table in database 1 is referring OrderedBy in Orders table.
I have Created 2 different context.
now i will create 2 queries for 2 different context and will make join on these queries on UserId and OrderedBy like:
List<OrderDetails> GetOrderDetails()
{
var users = this.TestDb1ModelUnit.GetRepository<User_Login>().GetAll();
var orders = this.TestDb2ModelUnit.GetRepository<OrderDetail>().GetAll();
var orderDetails = users.Join(orders,
usr => usr.User_Id,
ord => ord.OrderedBy,
(usr, ord) => new { usr, ord }
).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...
};

Use multiple left joins to set DTO property inside select new linq query

I have the following code inside an MVC 6 (beta8) controller:
public IActionResult Get()
{
var districtsdetails = from districts in _ctx.District
select new
{
Id = districts.Id,
CountyFP = districts.County.FIPSCode,
DirectorName = districts.DirectorName,
Email = districts.Email,
EstStudentPop = districts.EstStudentPop,
Name = districts.Name,
Phone = districts.Phone,
Ranking = districts.Ranking,
RANumber = districts.RANumber,
SchoolCount = districts.SchoolCount,
Coop = districts.Coop.Name,
County = districts.County.Name,
Distributors = (from district in _ctx.District
join districtdistributor in _ctx.DistrictDistributor on district.Id equals districtdistributor.DistrictId
into group1
from g1 in group1.DefaultIfEmpty()
join distributor in _ctx.Distributor on g1.DistributorId equals distributor.Id
into group2
from g2 in group2.DefaultIfEmpty()
where district.Id == districts.Id
select new { g2.Id, g2.Name })
};
if (districtsdetails == null)
return HttpNotFound();
return new JsonResult(districtsdetails);
}
The problem is in the Distributors property setter.
I have District, DistrictDistributor, and Distributor entities in my context (and matching tables in my db). There is a many to many relationship between District and Distributor, with DistrictDistributor mapping the many to many relationship between the two. In my DistrictDetailsDTO I'm attempting to bridge the DistrictDistributor gap so I can just do DistrictDetailsDTO.Distributors ... All this is being serialized to Json as you can see by the JsonResult().
In the Distributor = (...) I am trying to effectively reproduce this SQL:
select (...)
from [District] D
left join [DistrictDistributor] DD on
DD.DistrictId = D.Id
left join [Distributor] Db on
Db.Id = DD.DistributorId
where id = 57
However, in my linq 57 would be districts.Id since I'm returning all Districts.
Please HELP I'm going CRAZY! No matter what I try along these lines produces a:
HTTP Error 502.3 - Bad Gateway
The specified CGI application encountered an error and the server terminated the process.
Here is how I think it could be resolved.
First, your query - the hard way. You don't need left joins here at all. They would be needed if you were producing a joined result set (SelectMany), but since that's not the case, you can use the following and let EF do it's magic to make it work:
var query =
from district in _ctx.District.AsNoTracking()
select new
{
Id = district.Id,
Name = district.Name,
// the rest of the district related fields
// ...
Distributors =
from dd in _cxt.DistrictDistributor
where dd.DistrictId == district.Id
join d in _ctx.Distributor on dd.DistributorId equals d.Id
select new { d.Id, d.Name }
};
Second - the easy way. One of the cool things of EF is to describe your model with navigation properties and properly configured relationships. This way you can almost forget about manual joins and let EF do whatever is necessary to satisfy your queries. In your case, the proper model would have District.Distributors and Distributor.Districts navigation properties, and the same result could be achieved with the following simple query:
var query =
from district in _ctx.District.AsNoTracking()
select new
{
Id = district.Id,
Name = district.Name,
// the rest of the district related fields
// ...
Distributors = district.Distributors.Select(d => new { d.Id, d.Name })
};

Select data from 3 tables with Linq to SQL

I have 3 tables. Orders, OrderItems and OrderItemServices. Each order can contain multiple OrderItems and each OrderItem can contain multiple OrderItemServices.
I want to get a list of data of all orders from these tables in Linq. I could write a join but how do I make an anonymous data type to in select clasue which can give me Order list in this hierarchy?
If I use navigation properties and then select OrderItemServices in side select clause shown below it would fire individual select query for each OrderItemService which I want to avoid.
from order in Orders
select new
{
ActiveOrders = order,
ActiveOrderItems =order.OrderItems,
ActiveServices = order.OrderItems.Select(o => o.OrderItemServices)
}
Is it possible to group each order with a structure of multiple items inside it and multiple services inside items?
Refer msdn to start on LINQ To SQL
To get data from three tables you can get idea from the following simple example
var data = (from product in context.Products
from department in context.Departments
from category in context.Categories
where product.DeptId == department.DeptId
&& product.CatId == category.CatId
select new
{
product.Code,
product.Name,
department.Name,
category.Name
}).Distinct.ToList();
You have to set up your context to use eager loading:
var context = new MyDataContext();
var options = new DataLoadOptions();
options.LoadWith<Orders>(x => x.OrderItems);
options.LoadWith<OrderItems>(x => x.OrderItemServices);
context.LoadOptions = options;
var query = from order in context.Orders // ... etc
Then sub items will be included in initial query result and won't cause additional requests to the database. This will use JOIN internally to retrieve all the data in one go. You can check generated SQL using SQL Server Profiler.
http://blog.stevensanderson.com/2007/12/02/linq-to-sql-lazy-and-eager-loading-hiccups/

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