Reputation: 175
please I'm working on a ASP.NET MVC
project with Entity Framework
, and in a function I want it to return data structured by a Model ( I use LINQ query to retrieve data that the function will return it ).
Everything is fine when LINQ
query has data, but when LINQ
query has no data I got this Error :
Error :
Sequence contains no elements
Function :
public static List<ABS_model> SELECT_Related_With_STG_Details(string STG)
{
var R = (from A in SCHOOL_DB_Context.Con.ABS
join S in SCHOOL_DB_Context.Con.STGs on A.STG_ABS equals S.CD_STG
join U in SCHOOL_DB_Context.Con.UFs on A.UF_ABS equals U.CD_UF
where A.STG_ABS == STG
select new ABS_model {
N_ABS = A.N_ABS,
STG_ABS = A.STG_ABS,
NM_STG = S.NM_STG,
PRN_STG = S.PRN_STG,
DT_ABS = A.DT_ABS,
UF_ABS = U.NM_UF,
INTTL_UF = U.NM_UF,
JSTF_ABS = A.JSTF_ABS,
JSTF_DOC_ABS = A.JSTF_DOC_ABS
}
).ToList();
return R;
}
So I want to return Null model if Query has no record ( If I can ).
So please any help?
Upvotes: 0
Views: 800
Reputation: 339
As Priyank Panchal mentioned
use :
var R = (from A in SCHOOL_DB_Context.Con.ABS
join S in SCHOOL_DB_Context.Con.STGs on A.STG_ABS equals S.CD_STG
join U in SCHOOL_DB_Context.Con.UFs on A.UF_ABS equals U.CD_UF
where A.STG_ABS == STG
select new ABS_model {
N_ABS = A.N_ABS,
STG_ABS = A.STG_ABS,
NM_STG = S.NM_STG,
PRN_STG = S.PRN_STG,
DT_ABS = A.DT_ABS,
UF_ABS = U.NM_UF,
INTTL_UF = U.NM_UF,
JSTF_ABS = A.JSTF_ABS,
JSTF_DOC_ABS = A.JSTF_DOC_ABS
}
).ToList();
return R.Any() ? R : null
Upvotes: 0
Reputation: 310
Try this out, should work:
var R = from A in SCHOOL_DB_Context.Con.ABS
join S in SCHOOL_DB_Context.Con.STGs
on A.STG_ABS equals S.CD_STG
join U in SCHOOL_DB_Context.Con.UFs
on A.UF_ABS equals U.CD_UF
where A.STG_ABS == STG
select new ABS_model
{
N_ABS = A.N_ABS,
STG_ABS = A.STG_ABS,
NM_STG = S.NM_STG,
PRN_STG = S.PRN_STG,
DT_ABS = A.DT_ABS,
UF_ABS = U.NM_UF,
INTTL_UF = U.NM_UF,
JSTF_ABS = A.JSTF_ABS,
JSTF_DOC_ABS = A.JSTF_DOC_ABS
};
if(R.Any())
{
return R.ToList();
}
else
{
return null;
}
Upvotes: 1