Left outer join in linq on three table - c#

var response = ( from e in db.tblEvents
join f in db.tblEventTypes on e.FightTypeId equals f.eventTypeId
into egroup
from e in egroup.DefaultIfEmpty()
join w in db.tblUserWebApp on e.ModifiedUserId equals w.Id
orderby e.LastUserModified descending
select new {
FightTypeName = f.eventTypeName,
EventID = e.EventID,
FightTypeId=e.FightTypeId,
Title = e.Title,
Date = e.Date,
Location = e.Location,
UserSelectFavoriteFlag =e.UserSelectFavoriteFlag ,
Price=e.Price,
UserPredictionFlag=e.UserPredictionFlag,
PredictionStartDate= e.PredictionStartDate ,
PredictionEndDate = e.PredictionEndDate,
ModifiedUserId = w.Id,
ModifiedUser = w.LoginName,
LastUserModified = e.LastUserModified,
});
return Ok(response);
how can i use left outer join since i have 3 table to join and i want to get all data from tblEvents table

Try this query
var response = ( from e in db.tblEventTypes
from f in db.tblEvents.where(x=>x.FightTypeId ==e.eventTypeId).DefaultIfEmpty()
from w in db.tblUserWebApp.where(x=>x.Id==f.ModifiedUserId)
orderby f.LastUserModified descending
select new {
FightTypeName = e.eventTypeName,
EventID = f.EventID,
FightTypeId=f.FightTypeId,
Title = f.Title,
Date = f.Date,
Location = f.Location,
UserSelectFavoriteFlag =f.UserSelectFavoriteFlag ,
Price=f.Price,
UserPredictionFlag=f.UserPredictionFlag,
PredictionStartDate= f.PredictionStartDate ,
PredictionEndDate = f.PredictionEndDate,
ModifiedUserId = w.Id,
ModifiedUser = w.LoginName,
LastUserModified = f.LastUserModified,
});

Related

The specified LINQ expression contains references to queries that are associated with different contexts c#

I have this simple function that returns a query, but when I try to join 2 tables in different databases, the error raised: The specified LINQ expression contains references to queries that are associated with different contexts.
here is my code.
private object projectcycleFilter(int? pid, int? cid, int UserId)
{
string[] res = { null, "" };
int?[] resint = { null, 0 };
var access_user = (from p in geotagging.webpages_UsersInRoles join s in geotagging.UserProfiles on p.UserId equals s.UserId where p.UserId == UserId select p).ToList();
var x = new object();
var geotaggingquery = (from xx in geotagging.sub_project select xx).AsEnumerable();
var nfmsquery = (from p in nfmsdb.request_for_refund join lr in nfmsdb.lib_regions on p.region_code equals lr.region_code join lp in nfmsdb.lib_provinces on p.prov_code equals lp.prov_code join lc in nfmsdb.lib_cities on p.city_code equals lc.city_code join lb in nfmsdb.lib_brgy on p.brgy_code equals lb.brgy_code join gts in geotaggingquery on p.sub_project_id equals gts.sub_project_id select new { lb, lc, lp, lr, p, gts }).AsEnumerable();
if (access_user.Select(x => x.RoleId).FirstOrDefault() > 2)
{
nfmsquery = (from p in nfmsdb.request_for_refund join lr in nfmsdb.lib_regions on p.region_code equals lr.region_code join lp in nfmsdb.lib_provinces on p.prov_code equals lp.prov_code join lc in nfmsdb.lib_cities on p.city_code equals lc.city_code join lb in nfmsdb.lib_brgy on p.brgy_code equals lb.brgy_code join gt in nfmsdb.user_municipal_access on p.city_code equals gt.city_code join gts in geotaggingquery on p.sub_project_id equals gts.sub_project_id where gt.user_id == UserId && gt.selected == true select new { lb, lc, lp, lr, p, gts }).AsEnumerable();
}
if (!resint.Contains(pid))
{
nfmsquery = nfmsquery.Where(x => x.gts.project_type_id == pid);
}
if (!resint.Contains(cid))
{
nfmsquery = nfmsquery.Where(x => x.gts.cycle_id == cid);
}
var result = nfmsquery.Select(x => new
{
sub_project_id = x.p.sub_project_id,
sub_project_name = x.p.sub_project_name,
region_name = x.lr.region_name,
region_code = x.lr.region_code,
prov_name = x.lp.prov_name,
prov_code = x.lp.prov_code,
city_name = x.lc.city_name,
city_code = x.lc.city_code,
brgy_code = x.lb.brgy_code,
brgy_name = x.lb.brgy_name,
request_for_refund_id = x.p.request_for_refund_id,
total_sub_project_cost = x.p.total_sub_project_cost,
total_program_cost = x.p.total_program_cost,
region_director = x.p.region_director,
lbp_branch = x.p.lbp_branch,
address = x.p.address,
lcc_amount = x.p.lcc_amount,
account_name = x.p.account_name,
bank_no = x.p.bank_no,
amount_requested = x.p.amount_requested,
tranche_id = x.p.tranche_id,
prev_amount_release = x.p.prev_amount_release,
cumul_total_request = x.p.cumul_total_request,
date_created = x.p.date_created,
date_requested = x.p.date_requested,
brgy_chair_name = x.p.brgy_chair_name,
bspmc_name = x.p.bspmc_name,
ac_name = x.p.ac_name,
lprao_name = x.p.lprao_name,
lprao_date = x.p.lprao_date,
rpc_name = x.p.rpc_name,
rpm_name = x.p.rpm_name,
ac_date = x.p.ac_date,
rpc_date = x.p.rpc_date,
rpm_date = x.p.rpm_date,
updated_by = x.p.updated_by,
date_updated = x.p.date_updated,
isdeleted = x.p.isdeleted,
}).ToList();
return result;
}
I also try var geotaggingquery = (from xx in geotagging.sub_project select xx).ToList() and `var nfmsquery = (from p in nfmsdb.request_for_refund join lr in nfmsdb.lib_regions on p.region_code equals lr.region_code join lp in nfmsdb.lib_provinces on p.prov_code equals lp.prov_code join lc in nfmsdb.lib_cities on p.city_code equals lc.city_code join lb in nfmsdb.lib_brgy on p.brgy_code equals lb.brgy_code join gts in geotaggingquery on p.sub_project_id equals gts.sub_project_id select new { lb, lc, lp, lr, p, gts }).ToList();, nothing happens.
Thanks in advance

SQL to Linq: left join

I need to write linq query. I tried to write example in sql and it works great but I didn't manage to convert it to proper linq
This is my working sql query:
SELECT
pr.descr as product,
prm.Descr
, px.Value AS ParamValue
, prm.Unit AS Unit
, gx.TcPos
FROM [Product] pr
JOIN [PrGroup] prg ON pr.GroupId = prg.Id
LEFT JOIN [PrParamGroup] pg ON ISNULL(pr.PrParamGroupId, prg.PrParamGroupId) = pg.Id
CROSS JOIN [PrParam] prm
LEFT JOIN [PrParam2ProductX] px ON pr.Id = px.ProductId AND prm.Id = px.PrParamId
LEFT JOIN [PrParam2GroupX] gx ON prm.Id = gx.PrParamId AND pg.Id = gx.PrParamGroupId
WHERE
pr.Id = 123 AND
(px.PrParamId IS NOT NULL OR gx.PrParamId IS NOT NULL)
AND (gx.PrParamId <> -1 OR gx.PrParamId IS NULL)
AND (gx.PrParamId IS NOT NULL)
This is my linq attempt:
var productsDesc = (from pr in context.Product.Where(m => m.Id == 123)
join prg in context.PrGroup
on pr.GroupId equals prg.Id
join pg in context.PrParamGroup
on pr.PrParamGroupId equals pg.Id
from prm in context.PrParam
join px in context.PrParam2ProductX
on new { a = pr.Id, b = px.ProductId } equals new { a = prm.Id, b = px.PrParamId }
join gx in context.PrParam2GroupX
on new { prm.Id = gx.PrParamId } equals new { pg.Id = gx.PrParamGroupId }
select new
{
Name = prm.Descr,
Value = px.Value,
Unit = prm.Unit ?? ""
}).ToList();
Your linq dont implement left join and cross join
try this
var productsDesc = (from pr in context.Product.Where(m => m.Id == 123)
join prg in context.PrGroup
on pr.GroupId equals prg.Id
join pg in context.PrParamGroup
on pr.PrParamGroupId equals pg.Id into tmp1
from t1 in tmp1.DefaultIfEmpty()
from prm in context.PrParam
join px in context.PrParam2ProductX
on new { a = pr.Id, b = px.ProductId } equals new { a = prm.Id, b = px.PrParamId } into tmp2
from t2 in tmp2.DefaultIfEmpty()
join gx in context.PrParam2GroupX
on new { prm.Id = gx.PrParamId } equals new { pg.Id = gx.PrParamGroupId } into tmp3
from t3 in tmp3.DefaultIfEmpty()
select new
{
Name = prm.Descr,
Value = t2.Value,
Unit = prm.Unit ?? ""
}).ToList();

flatten out webapi EF using DTO and linq- using IF/THEN

I am attempting to flatten out my webapi EF using DTO's. So far I have the below statement working correctly. Now I want to add a layer of complexity stating a IF/THEN. I put a fake code in the first line of SELECT NEW SECTION.
Can someone please assist?
var query = (
from acctTbl in db.Accounts
join tradeTbl in db.Trades on acctTbl.AccountID equals tradeTbl.AccountID into ts
from tradeTbl in ts.DefaultIfEmpty()
join mapClientAcct in db.Mapping_ClientAccounts on acctTbl.AccountID equals mapClientAcct.AccountID
join clientTbl in db.Clients on mapClientAcct.ClientID equals clientTbl.ClientID
join mapUserClient in db.Mapping_UserClients on clientTbl.ClientID equals mapUserClient.ClientID
join aspNetUser in db.AspNetUsers on mapUserClient.AspNetUsersID equals aspNetUser.Id
join mktData in db.MarketDatas on tradeTbl.MarketDataID equals mktData.MarketDataID into ms
from mktData in ms.DefaultIfEmpty()
join mktCode in db.GMI_MarketCodes on tradeTbl.GMI_MarketCodesID equals mktCode.GMI_MarketCodesID into mc
from mktCode in mc.DefaultIfEmpty()
join Mgrs in db.Managers on acctTbl.ManagerID equals Mgrs.ManagerID
join FxMkts in db.ForexMarkets on mktData.crncy equals FxMkts.CurrencySymbol into fm
from FxMkts in fm.DefaultIfEmpty()
where acctTbl.AccountActive == true
&& clientTbl.ClientID == clientID
&& aspNetUser.UserName == username
select new TradeDetailDTO()
{
--THIS IS WHAT I WANT TO DO!!!
IF tradeTblIdentifier == "F" THEN 'yes'
ELSE 'no'
-------------------------
Filedate = tradeTbl.Filedate,
Quantity = tradeTbl.Quantity,
Month = tradeTbl.Month,
Strike = tradeTbl.Strike,
PutCall = tradeTbl.PutCall,
Prompt = tradeTbl.Prompt,
StmtPrice = tradeTbl.Price,
ShortDesc = mktCode.ShortDesc,
Sector = mktCode.Sector,
ExchName = mktCode.ExchName,
BBSymbol = mktData.BBSymbol,
BBName = mktData.Name,
fut_Val_Pt = mktData.fut_Val_Pt,
crncy = mktData.crncy,
fut_tick_size = mktData.fut_tick_size,
fut_tick_val = mktData.fut_tick_val,
fut_init_spec_ml = mktData.fut_init_spec_ml,
last_price = mktData.last_price,
bid = mktData.bid,
ask = mktData.ask,
px_settle_last_dt_rt = mktData.px_settle_last_dt_rt,
px_settle_actual_rt = mktData.px_settle_actual_rt,
chg_on_day = mktData.chg_on_day,
prev_close_value_realtime = mktData.prev_close_value_realtime,
AccountNumber = acctTbl.AccountNumber,
TradeLevel = acctTbl.TradeLevel,
ManagerName = Mgrs.ManagerName,
ManagerShortCode = Mgrs.ManagerShortCode,
ForexLastPrice = db.MarketDatas.FirstOrDefault(x => x.BBSymbol == mktData.crncy + " BGN CURNCY") == null ? 1: db.MarketDatas.FirstOrDefault(x => x.BBSymbol == mktData.crncy + " BGN CURNCY").last_price,
//ForexLastPrice = FxMkts.LastPrice, ORIGINAL
TopdayIdentifier = "P",
DailyPercentage = acctTbl.DailyPercentage,
AccountType = acctTbl.AccountType
}
);
If i understood you correctly you want something like this:
var query = (
from acctTbl in db.Accounts
join tradeTbl in db.Trades on acctTbl.AccountID equals tradeTbl.AccountID into ts
from tradeTbl in ts.DefaultIfEmpty()
join mapClientAcct in db.Mapping_ClientAccounts on acctTbl.AccountID equals mapClientAcct.AccountID
join clientTbl in db.Clients on mapClientAcct.ClientID equals clientTbl.ClientID
join mapUserClient in db.Mapping_UserClients on clientTbl.ClientID equals mapUserClient.ClientID
join aspNetUser in db.AspNetUsers on mapUserClient.AspNetUsersID equals aspNetUser.Id
join mktData in db.MarketDatas on tradeTbl.MarketDataID equals mktData.MarketDataID into ms
from mktData in ms.DefaultIfEmpty()
join mktCode in db.GMI_MarketCodes on tradeTbl.GMI_MarketCodesID equals mktCode.GMI_MarketCodesID into mc
from mktCode in mc.DefaultIfEmpty()
join Mgrs in db.Managers on acctTbl.ManagerID equals Mgrs.ManagerID
join FxMkts in db.ForexMarkets on mktData.crncy equals FxMkts.CurrencySymbol into fm
from FxMkts in fm.DefaultIfEmpty()
where acctTbl.AccountActive == true
&& clientTbl.ClientID == clientID
&& aspNetUser.UserName == username
select new TradeDetailDTO()
{
YesNo = tradeTbl.Identifier == "F"?"yes":"no",
Filedate = tradeTbl.Filedate,
Quantity = tradeTbl.Quantity,
Month = tradeTbl.Month,
Strike = tradeTbl.Strike,
PutCall = tradeTbl.PutCall,
Prompt = tradeTbl.Prompt,
StmtPrice = tradeTbl.Price,
ShortDesc = mktCode.ShortDesc,
Sector = mktCode.Sector,
ExchName = mktCode.ExchName,
BBSymbol = mktData.BBSymbol,
BBName = mktData.Name,
fut_Val_Pt = mktData.fut_Val_Pt,
crncy = mktData.crncy,
fut_tick_size = mktData.fut_tick_size,
fut_tick_val = mktData.fut_tick_val,
fut_init_spec_ml = mktData.fut_init_spec_ml,
last_price = mktData.last_price,
bid = mktData.bid,
ask = mktData.ask,
px_settle_last_dt_rt = mktData.px_settle_last_dt_rt,
px_settle_actual_rt = mktData.px_settle_actual_rt,
chg_on_day = mktData.chg_on_day,
prev_close_value_realtime = mktData.prev_close_value_realtime,
AccountNumber = acctTbl.AccountNumber,
TradeLevel = acctTbl.TradeLevel,
ManagerName = Mgrs.ManagerName,
ManagerShortCode = Mgrs.ManagerShortCode,
ForexLastPrice = db.MarketDatas.FirstOrDefault(x => x.BBSymbol == mktData.crncy + " BGN CURNCY") == null ? 1: db.MarketDatas.FirstOrDefault(x => x.BBSymbol == mktData.crncy + " BGN CURNCY").last_price,
//ForexLastPrice = FxMkts.LastPrice, ORIGINAL
TopdayIdentifier = "P",
DailyPercentage = acctTbl.DailyPercentage,
AccountType = acctTbl.AccountType
}
);

Linq To Sql Skip Take

I want to save each icon path into a variable, from the query bellow , only PathIcon1 has value . The remain path icon are empty
Query
using (CarteringServiceClientDataContext dc = new CarteringServiceClientDataContext())
{
result = (from a in dc.GetTable<tblSupplier>()
join b in dc.GetTable<tblCity>()
on a.CityId equals b.Id
join c in dc.GetTable<tblZone>()
on b.ZoneId equals c.Id
let r = (from re in dc.GetTable<tblClientReview>()
where re.SupplierId == a.Id
select re.note).Average()
let i = (from im in dc.GetTable<tblSupplierItem>()
where im.SupplierId == a.Id
select im.tblItem.IconPath).ToArray()
select new SearchResult
{
CompanyId = a.Id,
CompanyName = a.Company,
Localisation = a.Locality,
City = b.Name,
Zone = c.Name,
Rating = r.ToString(),
PathIcon1 = i.Take(1).SingleOrDefault(),
PathIcon2 = i.Skip(1).Take(1).SingleOrDefault(),
PathIcon3 = i.Skip(2).Take(1).SingleOrDefault(),
PathIcon4 = i.Skip(3).Take(1).SingleOrDefault(),
PathIcon5 = i.Skip(4).Take(1).SingleOrDefault()
}).ToList<SearchResult>();
}
A part from PathIcon1, the remaing PathIcon are null
using (CarteringServiceClientDataContext dc = new CarteringServiceClientDataContext())
{
result = (from a in dc.GetTable<tblSupplier>()
join b in dc.GetTable<tblCity>()
on a.CityId equals b.Id
join c in dc.GetTable<tblZone>()
on b.ZoneId equals c.Id
let r = (from re in dc.GetTable<tblClientReview>()
where re.SupplierId == a.Id
select re.note).Average()
let i = (from im in dc.GetTable<tblSupplierItem>()
where im.SupplierId == a.Id
select im.tblItem.IconPath).ToArray().Add("test")
select new SearchResult
{
CompanyId = a.Id,
CompanyName = a.Company,
Localisation = a.Locality,
City = b.Name,
Zone = c.Name,
Rating = r.ToString(),
PathIcon1 = i.Take(1).SingleOrDefault(),
PathIcon2 = i.Skip(1).Take(1).SingleOrDefault(),
PathIcon3 = i.Skip(2).Take(1).SingleOrDefault(),
PathIcon4 = i.Skip(3).Take(1).SingleOrDefault(),
PathIcon5 = i.Skip(4).Take(1).SingleOrDefault()
}).ToList<SearchResult>();
}
Try this if you are get PathIcon2 value as "test" your problem isn't skip or take. Just i list includes one item. Adn I think so.

How to convert SQL query with Unions to LINQ?

How to convert this one to LINQ?
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
where d.UserID = 1
/* Friends posts */
Union
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
join Friends as fr
on d.UserID = fr.FriendID
where fr.UserID = 1
/* My followings */
Union
select d.UserID, d.Content, d.UpdateTime
from DiaryPosts as d
join Followers as fl
on d.UserID = fl.FollowerID
where fl.UserID = 1
/* order by UpdateTime desc */
order by 3 desc
I tried this:
var diaryPosts = (from d in db.DiaryPosts
join e in db.EstadosDeAlma
on d.EstadosDeAlmaID equals e.ID
join u in db.User
on d.UserID equals u.ID
join fr in db.Friends
on d.UserID equals fr.FriendID
where fr.UserID == userset.ID
join fl in db.Followers
on d.UserID equals fl.UserID
where fl.FollowerID == userset.ID
orderby d.ID descending
select new DiaryPostsSet
{
PostID = d.ID,
EstadoDeAlmaID = e.ID,
EstadoDeAlma = e.Title,
Author = u.Nickname,
Thumbnail = u.Thumbnail,
AuthorComment = d.Content,
UserID = u.ID,
IsDuplicated = d.IsDuplicated,
FriendID = d.FriendID,
FriendName = u.Nickname,
Time = d.UpdateTime,
MessagesCount = d.FriendMessages.Count(m => m.DiaryPostsID == d.ID)
}).Take(6).ToList();
It doesn't show me any result. I tried with EF clauses but when I have Union, I don't know how to perform the next Join.
Could anyone help me please?
There is a Union Method in LINQ
Here is a hint. When things get difficult break them down, then simplify. I will help you break down the problem and leave the simplification to you.
var query1 = (from d in db.DiaryPosts
where d.UserID = 1
select new {
UserID = d.UserID
Content = d.Content
UpdateTime = d.UpdateTime
}).ToList();
var query2 = (from d in db.DiaryPosts
join f in db.Friends
on d.UserId = f.FriendId
where f.UserId = 1
select new {
UserID = d.UserID
Content = d.Content
UpdateTime = d.UpdateTime
}).ToList();
var query3 = (from d in db.DiaryPosts
join f in db.Followers
on d.UserId = f.FollowerID
where f.UserId = 1
select new {
UserID = d.UserID
Content = d.Content
UpdateTime = d.UpdateTime
}).ToList();
var myunionQuery = query1.Union(query2).Union(query3).OrderBy(d => d.UpdateTime);

Categories