I have SQL query as:
SELECT b.firstName + ' ' + b.lastName AS Name, a.*
FROM EH_PP_TeacherObservations AS a INNER JOIN
account AS b ON a.EH_PP_TeacherAcctId = b.id LEFT JOIN
EH_PP_ObserverStatus AS c ON c.EH_PP_AcctId = b.id
WHERE a.EH_PP_TOSRT_TeacherObservationStatusIDEH = '0B823C51-EEAE-4490-B0EC-C1F0B1206AEB' AND
c.EH_PP_O_isObserver = 1
I wanted to have same query in linq.
I made it as follows:
List<Entity.account> list = new List<Entity.account>();
list = (
from a in context.EH_PP_TeacherObservations
join b in context.accounts on new { EH_PP_TeacherAcctId = a.EH_PP_TeacherAcctId } equals new { EH_PP_TeacherAcctId = b.id }
join c in context.EH_PP_ObserverStatus on new { EH_PP_AcctId = b.id } equals new { EH_PP_AcctId = Convert.ToGuid(c.EH_PP_AcctId) } into c_join
from c in c_join.DefaultIfEmpty()
where
a.EH_PP_TOSRT_TeacherObservationStatusIDEH == new Guid("0B823C51-EEAE-4490-B0EC-C1F0B1206AEB") &&
c.EH_PP_O_isObserver == true
select new
{
Name = (b.firstName + " " + b.lastName),
EH_PP_ObservationID = a.EH_PP_ObservationID,
EH_PP_TE_TeacherEvalID = a.EH_PP_TE_TeacherEvalID,
EH_PP_TOT_ObservationStartDateTime = a.EH_PP_TOT_ObservationStartDateTime,
EH_PP_TOT_ObservationEndDateTime = a.EH_PP_TOT_ObservationEndDateTime,
EH_PP_TOT_Announced = a.EH_PP_TOT_Announced,
EH_PP_TOT_ObservationNum = a.EH_PP_TOT_ObservationNum,
EH_PP_TeacherAcctId = a.EH_PP_TeacherAcctId,
EH_PP_ObserverAcctID = a.EH_PP_ObserverAcctID,
EH_PP_TOSRT_TeacherObservationStatusIDEH = a.EH_PP_TOSRT_TeacherObservationStatusIDEH
}
).ToList<Entity.account>();
But its giving me error on
join b in context.accounts on new { EH_PP_TeacherAcctId = a.EH_PP_TeacherAcctId } equals new { EH_PP_TeacherAcctId = b.id }
error is on 'join' word.
Type of one of expressions in the join clause is incorrect.
Type interface failed to call to 'join'
Please help me.
What is the mistake???
try this
List<Entity.account> list = new List<Entity.account>();
list = (
from a in context.EH_PP_TeacherObservations
join b in context.accounts on b.id equals a.EH_PP_TeacherAcctId
join c in context.EH_PP_ObserverStatus on Convert.ToGuid(c.EH_PP_AcctId) equals b.id into c_join
from c in c_join.DefaultIfEmpty()
where
a.EH_PP_TOSRT_TeacherObservationStatusIDEH == new Guid("0B823C51-EEAE-4490-B0EC-C1F0B1206AEB") &&
c.EH_PP_O_isObserver == true
select new
{
Name = (b.firstName + " " + b.lastName),
EH_PP_ObservationID = a.EH_PP_ObservationID,
EH_PP_TE_TeacherEvalID = a.EH_PP_TE_TeacherEvalID,
EH_PP_TOT_ObservationStartDateTime = a.EH_PP_TOT_ObservationStartDateTime,
EH_PP_TOT_ObservationEndDateTime = a.EH_PP_TOT_ObservationEndDateTime,
EH_PP_TOT_Announced = a.EH_PP_TOT_Announced,
EH_PP_TOT_ObservationNum = a.EH_PP_TOT_ObservationNum,
EH_PP_TeacherAcctId = a.EH_PP_TeacherAcctId,
EH_PP_ObserverAcctID = a.EH_PP_ObserverAcctID,
EH_PP_TOSRT_TeacherObservationStatusIDEH = a.EH_PP_TOSRT_TeacherObservationStatusIDEH
}
).ToList<Entity.account>();
Related
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
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();
I have this query but I need to add a where clause that uses 'Contains()' so I can check the db for a list of accountIDs, the reason I need to do it this way is because I have to first check if there are any accountID's and if there are it must execute the 'Contains()' in the where clause but the compiler complains if I try do it this way but given what the method has to do I can't figure out another way to do it given the fact that there are so many tables joined in the query.
My code:
bool UseAcc = false;
if (accountIds != null && accountIds.Count > 0)
{
UseAcc = true;
}
var query = (from i in db.Incidents
join s in db.Sites on i.SiteID equals s.SiteID
join a in db.Accounts on i.AccountID equals a.AccountID
join st in db.Status on i.StatusID equals st.StatusID
join currentUser in db.Users on i.CurrentAssignedUser equals currentUser.UserID
join loggedByUser in db.Users on i.LoggedByUser equals loggedByUser.UserID
join createdByUser in db.Users on i.CreatedByUser equals createdByUser.UserID
join l in db.Locations on i.Location equals l.LocationID into locList
from loc in locList.DefaultIfEmpty()
join q in db.QuestionCategories on i.QuestionCategoryID equals q.QuestionCategoryID
join ia in db.IncidentActions on i.IncidentID equals ia.IncidentID into iaList
from actions in iaList.DefaultIfEmpty()
//If 'UseAcc' gets set to true then execute the contains section of the or statement
where (i.Active == true) &&
(UseAcc = false || a => accountIds.Contains(a.AccountID))
select new
{
Title = i.Title,
IncidentID = i.IncidentID,
StatusName = st.StatusName,
StatusID = i.StatusID,
ReferenceNumber = i.ReferenceNo,
AccountName = a.AccountName,
AccountID = i.AccountID,
SiteName = s.SiteName,
SiteID = i.SiteID,
LocationName = loc.LocationName,
LocationID = i.Location,
CatName = q.QuestionCategoryName,
CatID = i.QuestionCategoryID,
CurrentAssignedUser = currentUser.FirstName + " " + currentUser.LastName,
AssignedUserID = i.CurrentAssignedUser,
CreatedByUser = createdByUser.FirstName + " " + createdByUser.LastName,
DateCreated = i.LoggedDate,
DepartmentID = i.DepartmentID,
Logger = loggedByUser.FirstName + " " + loggedByUser.LastName,
LoggedBy = i.LoggedByUser,
EscalationCount = i.EscalationCount)
});
I would paste the whole method but its really big.
I have looked at examples online but they can't work either because alot of them use an AsQueryable with a single table and this query has many tables joined.
Please Help.
var accounts = db.Accounts.AsQueryable();
if (accountIds != null && accountIds.Count > 0)
{
accounts = accounts.Where(a => accountIds.Contains(a.AccountID));
}
var query = (from i in db.Incidents
join s in db.Sites on i.SiteID equals s.SiteID
join a in accounts on i.AccountID equals a.AccountID
join st in db.Status on i.StatusID equals st.StatusID
join currentUser in db.Users on i.CurrentAssignedUser equals currentUser.UserID
join loggedByUser in db.Users on i.LoggedByUser equals loggedByUser.UserID
join createdByUser in db.Users on i.CreatedByUser equals createdByUser.UserID
join l in db.Locations on i.Location equals l.LocationID into locList
from loc in locList.DefaultIfEmpty()
join q in db.QuestionCategories on i.QuestionCategoryID equals q.QuestionCategoryID
join ia in db.IncidentActions on i.IncidentID equals ia.IncidentID into iaList
from actions in iaList.DefaultIfEmpty()
select new
{
Title = i.Title,
IncidentID = i.IncidentID,
StatusName = st.StatusName,
StatusID = i.StatusID,
ReferenceNumber = i.ReferenceNo,
AccountName = a.AccountName,
AccountID = i.AccountID,
SiteName = s.SiteName,
SiteID = i.SiteID,
LocationName = loc.LocationName,
LocationID = i.Location,
CatName = q.QuestionCategoryName,
CatID = i.QuestionCategoryID,
CurrentAssignedUser = currentUser.FirstName + " " + currentUser.LastName,
AssignedUserID = i.CurrentAssignedUser,
CreatedByUser = createdByUser.FirstName + " " + createdByUser.LastName,
DateCreated = i.LoggedDate,
DepartmentID = i.DepartmentID,
Logger = loggedByUser.FirstName + " " + loggedByUser.LastName,
LoggedBy = i.LoggedByUser,
EscalationCount = i.EscalationCount)
});
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
}
);
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.