I am using Linq query and call method Like..
oPwd = objDecryptor.DecryptIt((c.Password.ToString())
it will return null value.
Means this will not working.
how I Resolve this.
Thanks..
var q =
from s in db.User
join c in db.EmailAccount on s.UserId equals c.UserId
join d in db.POPSettings
on c.PopSettingId equals d.POPSettingsId
where s.UserId == UserId && c.EmailId == EmailId
select new
{
oUserId = s.UserId,
oUserName = s.Name,
oEmailId = c.EmailId,
oEmailAccId = c.EmailAccId,
oPwd = objDecryptor.DecryptIt(c.Password.ToString()),
oServerName = d.ServerName,
oServerAdd = d.ServerAddress,
oPOPSettingId = d.POPSettingsId,
};
If that is LINQ-to-SQL or Entity Framework. You'll need to break it into steps (as it can't execute that at the DB). For example:
var q = from s in db.User
join c in db.EmailAccount on s.UserId equals c.UserId
join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId
where s.UserId == UserId && c.EmailId == EmailId
select new
{
oUserId = s.UserId,
oUserName = s.Name,
oEmailId = c.EmailId,
oEmailAccId = c.EmailAccId,
oPwd = c.Password,
oServerName = d.ServerName,
oServerAdd = d.ServerAddress,
oPOPSettingId = d.POPSettingsId,
};
then use AsEnumerable() to break "composition" against the back-end store:
var query2 = from row in q.AsEnumerable()
select new
{
row.oUserId,
row.oUserName,
row.oEmailId,
row.oEmailAccId,
oPwd = objDecryptor.DecryptIt(row.oPwd),
row.oServerName,
row.oServerAdd,
row.oPOPSettingId
};
var q = from s in db.User
join c in db.EmailAccount on s.UserId equals c.UserId
join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId
where s.UserId == UserId && c.EmailId == EmailId
select new
{
oUserId = s.UserId,
oUserName = s.Name,
oEmailId = c.EmailId,
oEmailAccId = c.EmailAccId,
oPwd = c.Password,
oServerName = d.ServerName,
oServerAdd = d.ServerAddress,
oPOPSettingId = d.POPSettingsId,
};
foreach (var item in q)
{
item.oPwd = objDecryptor.DecryptIt(row.oPwd),
}
we can use a foreach loop also to update a single property. do not need to select all property in next query.
This has nothing about Linq query. you need to debug method objDecryptor.DecryptIt
Related
I have the following part of code that works perfectly.
public Task<List<RsvItemsViewModel>> GetReservations(int company_ID)
{
try
{
// we cannot pass parameter as company_id . we use hard coded values as 1 for CompanyId.Must find a way to overcome this
return ((from a in gTravelDbContext.Set<Frsvitem>()
join d in gTravelDbContext.Set<Freserv>()
on a.Rsinum equals d.Rsvnum into gd from d in gd.Where(p1 => p1.CompanyId == 1)
join c in gTravelDbContext.Set<Fsupplier>()
on a.SupplId equals c.SupplId into gc from c in gc.Where(p1=>p1.CompanyId == 1)
join i in gTravelDbContext.Set<Fzone>()
on a.Rsizone equals i.Zoneid into gi
from i in gi.DefaultIfEmpty() where i.CompanyId == 1
join g in gTravelDbContext.Set<Fservtype>()
on a.Rsisertype equals g.Stypecode
join b in gTravelDbContext.Set<Fcustomer>()
on d.CustId equals b.CustId
join e in gTravelDbContext.Set<Fpaykind>()
on d.Rsvpaymethod equals e.Payid into ge
from e in ge.DefaultIfEmpty()
join f in gTravelDbContext.Set<Fsalesman>()
on d.Rsvsalescode equals f.Salescode into gf
from f in gf.DefaultIfEmpty()
join h in gTravelDbContext.Set<Fpinake>()
on d.Rsvakirosi equals h.Tblid into gh
from h in gh.Where(p => p.Tblcd == "yesno")
select new RsvItemsViewModel
{
Rsinum = a.Rsinum,
Stypename = g.Stypename,
Cuname = b.Cuname,
Rsvcuname = d.Rsvcuname,
Sumame = c.Suname,
Rsvakirosi = d.Rsvakirosi,
Yesno = h.Tbltext ,
Paytext = e.Paytext,
Salesname = f.Salesname,
Stypegroup = g.Stypegroup,
Company_id =d.CompanyId.GetValueOrDefault(),
Zonename = i.Zonename,
Rsisertype = a.Rsisertype,
Suppl_id = a.SupplId,
Xrhsh = d.Xrhsh,
Bpar_id = a.BparId
}
).ToListAsync());
}
catch (Exception)
{
throw;
}
}
The problem is that I want to pass company_ID as a parameter in linq and I want to substitute the Where(p1 => p1.CompanyId == 1) with Where(p1 => p1.CompanyId == company_ID )
I would be grateful if someone could help me.
Thank you
You have used GroupJoin in way, which is not supported by EF Core. GroupJoin has a lot of limitations and use it only if you need LEFT JOIN.
I have rewritten your query to be translatable:
var query =
from a in gTravelDbContext.Set<Frsvitem>()
from d in gTravelDbContext.Set<Freserv>().Where(d => d.Rsvnum == a.Rsinum && d.CompanyId == company_ID)
from c in gTravelDbContext.Set<Fsupplier>().Where(c => a.SupplId == c.SupplId && c.CompanyId == company_ID)
from i in gTravelDbContext.Set<Fzone>().Where(i => a.Rsizone == i.Zoneid && c.CompanyId == company_ID).DefaultIfEmpty()
join g in gTravelDbContext.Set<Fservtype>()
on a.Rsisertype equals g.Stypecode
join b in gTravelDbContext.Set<Fcustomer>()
on d.CustId equals b.CustId
join e in gTravelDbContext.Set<Fpaykind>()
on d.Rsvpaymethod equals e.Payid into ge
from e in ge.DefaultIfEmpty()
join f in gTravelDbContext.Set<Fsalesman>()
on d.Rsvsalescode equals f.Salescode into gf
from f in gf.DefaultIfEmpty()
from h in gTravelDbContext.Set<Fpinake>().Where(h => d.Rsvakirosi == h.Tblid && h.Tblcd == "yesno")
select new RsvItemsViewModel
{
Rsinum = a.Rsinum,
Stypename = g.Stypename,
Cuname = b.Cuname,
Rsvcuname = d.Rsvcuname,
Sumame = c.Suname,
Rsvakirosi = d.Rsvakirosi,
Yesno = h.Tbltext ,
Paytext = e.Paytext,
Salesname = f.Salesname,
Stypegroup = g.Stypegroup,
Company_id =d.CompanyId.GetValueOrDefault(),
Zonename = i.Zonename,
Rsisertype = a.Rsisertype,
Suppl_id = a.SupplId,
Xrhsh = d.Xrhsh,
Bpar_id = a.BparId
}
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
Here I want to join the out put of the first query(one column) to the result of the 2nd query to get a one result set. How can I merge them.(CONCAT doesn't work as required. eg: var query2 = query.concat(query1);)
var query = (from PP in _db.paymentPlans
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new {C,PP} by new {C.courseID} into totalRecievable
select new PdPpAppCourseModel
{
courseID = totalRecievable.Key.courseID,
totalAmount = totalRecievable.Sum(x => x.PP.totalAmount)
}).ToList();
var query1=(from PD in _db.paymentDetails
join PP in _db.paymentPlans on PD.paymentPlanID equals PP.paymentPlanID
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new { C,PD } by new { C.courseID, C.cricosCode, C.courseName } into paymentsCourseWise
select new PdPpAppCourseModel
{
courseID = paymentsCourseWise.Key.courseID,
cricosCode = paymentsCourseWise.Key.cricosCode,
courseName = paymentsCourseWise.Key.courseName,
paidAmount = paymentsCourseWise.Sum(x => x.PD.paidAmount)
}).ToList();
You could join query1 and query like this
var result = (from q1 in query1
join q in query on q1.courseID = q.courseID
select new PdPpAppCourseModel
{
courseID = q1.Key.courseID,
cricosCode = q1.Key.cricosCode,
courseName = q1.Key.courseName,
paidAmount = q1.Sum(x => x.PD.paidAmount),
totalAmount = q.totalAmount
}).ToList();
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.