I need to get one value of the q2.RoomId in this linq query as below and pass it to string variable . and is it possible to set alias column name for select ?
var result = from q1 in _db.DormApplications
join q2 in _db.DormRooms
on q1.DormRoomId equals q2.Id
where q1.Poster == username && q1.Review == EnableType.YES
&& now > q1.Sdate && now <q1.Edate
select new { q1.Name, q1.Sdate, q1.Edate, q1.DormRoomId,
q2.RoomId };
I tried this to get q2.RoomId ,
String room = result[4].ToString();
but still cannot work ,please anyone can help me ?
If you know the query will only return one row you can write:
var result = (from q1 in _db.DormApplications
join q2 in _db.DormRooms
on q1.DormRoomId equals q2.Id
where
q1.Poster == username && q1.Review == EnableType.YES
&& now > q1.Sdate && now <q1.Edate
select
new {
q1.Name,
q1.Sdate,
q1.Edate,
q1.DormRoomId,
q2.RoomId
}).FirstOrDefault();
var roomId = result.RoomId;
var Name = result.Name;
Related
I want to implement the following SQL statement using entity framework:
select coalesce(SUM(cdin_ActMortgageAmnt), 0)
from CRM.dbo.CDIndex,CRM.dbo.company
where comp_companyid = cdin_companyid
and comp_idcust like '%10319%'
and cdin_Deleted is null
and cdin_startunstufdate is not null
and cdin_Status = 'InProgress'
I tried to get the sum of cdin_ActMortgageAmnt:
Company c = db.Companies.Find(750);
var CGP = (from cd in db.CDIndexes
join com in db.Companies on cd.cdin_CompanyId equals com.Comp_CompanyId
where com.Comp_IdCust == c.Comp_IdCust &&
cd.cdin_Deleted == null &&
cd.cdin_startunstufdate == null &&
cd.cdin_Status == "InProgress"
select new
{
act = cd.cdin_ActMortgageAmnt == null ? 0 : cd.cdin_ActMortgageAmnt
}
);
var query = CGP.Sum(x => x.act);
lblSum.Text = query.ToString();
But the query returns null while tracing...
Hi i'm trying to convert this SQL script in Linq expression
but i donĀ“t know how do the MAX method in Linq
someone can help me?
thank you!
SELECT c.Nome,
c.NumeroRG,
f.Tipo,
f.Descricao,
f.DataHora,
f.IdCliente,
c.IdCliente,
f.IdFrequencia
FROM Cliente c, Frequencia f
WHERE f.Tipo = 1
AND c.IdCliente = f.IdCliente
AND cast(f.DataHora as date) = cast(getdate() as date)
AND f.IdFrequencia = (select MAX(fr.IdFrequencia)
from frequencia fr
where fr.IdCliente =c.IdCliente)
Perhaps something like this:
var query = from client in db.Cliente
join freq in db.Frequencia
on client.IdCliente equals freq.IdCliente
where freq.Tipo == 1
&& freq.DataHora.Date == DateTime.Now.Date
&& freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente)
Max(f => f.IdFrequencia)
select new { .... };
Maybe you need to replace DateTime.Now.Date/DateTime.Today with SqlFunctions.DatePart if you use LINQ-To-Entities, but you haven't mentioned that.
this worked well! thanks
var query = from client in db.Cliente
join freq in db.Frequencia
on client.IdCliente equals freq.IdCliente
where freq.Tipo == true
&& freq.DataHora.Value.Date == DateTime.Today.Date
&& freq.IdFrequencia == db.Frequencia.Where(f => f.IdCliente == client.IdCliente).Max(f => f.IdFrequencia)
select new { Nome = client.Nome, Descricao = freq.Descricao };
I am trying to grab all data from FDerive, however I am try to set a filter with a where clause. Unfortunately I am getting a nullreferencexpection when I touch spd when a row in spd is null.
var Result = from fpd in FDerive
join spd in SDerive
on new { fpd.PId, fpd.SId }
equals new { spd.PId, spd.SId } into allRows
from spd in allRows.DefaultIfEmpty()
where spd.SId == ""
|| spd.PId == ""
select new { fpd, spd };
How do I get around the null error?
DefaultIfEmpty<T> will return a set containing only one element with the default value of T - in this case null - if the source collection is empty. So spd will be null if there are no items returned in the join.
Try to a null check in the where clause
var Result =
...
where spd == null || spd.SId == "" || spd.PId == ""
select new { fpd, spd };
I found the answer at the bottom of the code in the following question
LINQ double left join
var results =
from person in students
join entry in subquery on person.FullName equals entry.AuthorFullName into personEntries
from personEntry in personEntries.DefaultIfEmpty()
orderby person.FullName
select new
{
PersonName = person.FullName,
BlogTitle = personEntry == null ? "" : personEntry.Title
};
I've made a query to get a list of articles, each bound to a "header",
so i retrieve the header plus the related articles and their properties.
The query works, however in its current style it is
Somewhat messy ( in my opinion)
The .ToList() takes way longer than i would expect.
Does anyone see any obvious reason for the speed-issue?
var offerheaders =
from o in dbcontext.F_CAB_OFFER_HEADERS
where
o.OFHD_FK_BUYER == userinfo.orgaTypeSequence
&& o.OFHD_VALID_FROM <= userinfo.selectedDate
&& o.OFHD_VALID_TO >= userinfo.selectedDate
&& o.OFHD_DELETED_YN == 0
&& o.OFHD_DELETED_BY_OWNER_YN == false
&& o.OFHD_OFFER_TYPE == userinfo.offerType
orderby o.OFHD_NO ascending
select o;
var offerlist =
from ofhd in offerheaders
select new {
ofhd = new {
OfferNo = ofhd.OFHD_NO,
OfferSequence = ofhd.OFHD_SEQUENCE,
ValidFrom = ofhd.OFHD_VALID_FROM,
ValidTo = ofhd.OFHD_VALID_TO,
OfferType = ofhd.OFHD_OFFER_TYPE,
Maingroup = new { cdmg_seq = ofhd.F_CAB_CD_MAIN_GROUP_TYPE.CDMG_SEQUENCE, Desc = ofhd.F_CAB_CD_MAIN_GROUP_TYPE.CDMG_DESC },
Supplier = new {
Name = ofhd.F_CAB_GROWER.F_CAB_ORGANISATION.ORGA_NAME,
Pic = ofhd.F_CAB_GROWER.F_CAB_ORGANISATION.ORGA_FK_PICTURE,
Seq = ofhd.F_CAB_GROWER.GROW_SEQUENCE
},
Caption = ofhd.OFHD_CAPTION,
Seperate = ofhd.OFHD_SHOW_SEPARATE_YN,
//ofdts = (from ofdt in dbcontext.F_CAB_OFFER_DETAILS.Where(x => x.OFDT_FK_OFFER_HEADER == ofhd.OFHD_SEQUENCE && x.OFDT_NUM_OF_ITEMS > 0 && x.OFDT_LATEST_DELIVERY_DATE_TIME > compareDateTime && x.OFDT_LATEST_ORDER_DATE_TIME > compareDateTime)
ofdts = from ofdt in dbcontext.F_CAB_OFFER_DETAILS
join props in dbcontext.F_CAB_CAB_PROP on ofdt.OFDT_FK_CAB_CODE equals props.PROP_FK_CABC_SEQ
join cabcode in dbcontext.F_CAB_CD_CAB_CODE on ofdt.OFDT_FK_CAB_CODE equals cabcode.CABC_SEQUENCE
join cabgroup in dbcontext.F_CAB_CD_CAB_GROUP on cabcode.CABC_FK_CAB_GROUP equals cabgroup.CDGR_SEQUENCE
join grouptype in dbcontext.F_CAB_CD_GROUP_TYPE on cabgroup.CDGR_FK_GROUP_TYPE equals grouptype.CDGT_SEQUENCE
join maingrouptype in dbcontext.F_CAB_CD_MAIN_GROUP_TYPE on grouptype.CDGT_FK_MAIN_GROUP equals maingrouptype.CDMG_SEQUENCE
join caca in dbcontext.F_CAB_CAB_CASK_MATRIX on ofdt.OFDT_FK_CACA_SEQ equals caca.CACA_SEQUENCE
join cask in dbcontext.F_CAB_CD_CASK on caca.CACA_FK_CASK equals cask.CDCA_SEQUENCE
join vbncode in dbcontext.F_CAB_CAB_VBN_MATRIX on cabcode.CABC_SEQUENCE equals vbncode.CVMA_FK_CAB_CODE
join grel in dbcontext.F_CAB_GENERAL_RELATIONS on ofdt.OFDT_FK_GREL_SEQ equals grel.GREL_SEQUENCE into greltable
from g_loj in greltable.DefaultIfEmpty()
where
ofdt.OFDT_FK_OFFER_HEADER == ofhd.OFHD_SEQUENCE
&& ofdt.OFDT_NUM_OF_ITEMS > 0
&& props.PROP_FK_CDLA_SEQ == userinfo.lang.CDLA_SEQUENCE
orderby props.PROP_CAB_DESC ascending
select new {
Desc = props.PROP_CAB_DESC,
Group = new { cdgr_seq = cabgroup.CDGR_SEQUENCE, Desc = cabgroup.CDGR_DESC },
Grouptype = new { grouptype.CDGT_SEQUENCE, Desc = grouptype.CDGT_DESC },
Properties = new CABProperties { props = props },
Price = ofdt.OFDT_ITEM_PRICE,
PIC_SEQ = ofdt.OFDT_FK_PICTURE ?? ((cabcode.CABC_FK_PICTURE ?? cabcode.CABC_SEQUENCE)),
PIC_URL = ofdt.OFDT_EXT_PICTURE_REF ?? "",
Seq = ofdt.OFDT_SEQUENCE,
Available = ofdt.OFDT_NUM_OF_ITEMS,
CabCode = ofdt.F_CAB_CD_CAB_CODE.CABC_CAB_CODE,
VBNCode = vbncode.CVMA_FK_VBN_CODE,
Remark = ofdt.OFDT_REMARK,
IsSpecial = ofdt.OFDT_SPECIAL_YN,
Arrived = inTransit ? ofdt.OFDT_ARRIVAL_DATE < DateTime.Now : true,
Cask = new CABCask { cask = cask, caca = caca },
Supplier = g_loj == null ? (ofdt.OFDT_SUPPLIER ?? "") : g_loj.GREL_NAME,
SupplierWeb = g_loj == null ? "" : g_loj.GREL_WEBSITE_URL,
SupplierLogo = g_loj == null ? ofhd.F_CAB_GROWER.F_CAB_ORGANISATION.ORGA_FK_PICTURE : g_loj.GREL_FK_PICT_SEQ,
SupplierSeq = g_loj == null ? -1 : g_loj.GREL_SEQUENCE,
}
}
};
userinfo.mainofferlist = offerlist.ToList();
As Daniel Kelly also mentioned the ToList function is where your query is executed, because these LinqToEntities queries are executed at the point where they are first enumerated, and ToList does that to be able to create a list.
Basically the reason why your querying takes so much time can be separated into two different reasons:
you are using too much projections and I thine (the parts with new {
})
your query has an incredible amount of join clauses
I would recommend to separate your query into subqueries, and run them separately like the first part in
...
select o
use
...
select o).ToList()
by breaking down the main query where you have a lot of subqueries it will be faster and much more readable, so you have less "messiness".
And last but not least you should create mapping for the anonymous objects, and use those classes other than projection that should speed up your query.
I'm confused about how to change this query to LINQ
select
CONTENT
from
(
select
CONTENT,
CAM_ID,
max(CAM_ID) over (partition by DOCUMENT_ID) MAX_ID
from
T_CAM_REVISION
where
DOCUMENT_ID = '101'
)
where
CAM_ID = MAX_ID
so I can get a single value of content.
There is no way to do max(...) over (...) in LINQ. Here is an equivalent query:
var maxCamID =
context.T_CAM_REVISION
.Where(rev => rev.DOCUMENT_ID == "101")
.Max(rev => rev.CAM_ID);
var query =
from rev in context.T_CAM_REVISION
where rev.CAM_ID == maxCamID
where rev.DOCUMENT_ID == "101"
select rev.CONTENT;
If you want only a single result:
var result =
context.T_CAM_REVISION
.First(rev => rev.CAM_ID == maxCamID
&& rev.DOCUMENT_ID == "101")
.CONTENT;