linq to entities nested select fillout - c#

I'm trying to return a result and a nested result in a linq to entities query.
Orders[] orderlist =
(from m in db.Orders.Include("OrderLines")
where
areas.Contains(m.Area)
&& m.Branch == branch
&& (m.OrderStatus == "1" || m.OrderStatus == "4")
&& m.SpecialInstrs == string.Empty
select m
HOW??---> m.OrderLines = m.OrderLines.Where(p => (p.LineType == "1" || p.LineType == "7") && p.MBomFlag != "C").ToArray()
).ToArray();
The problem is that the include returns all the FK'd OrderLines for each order when I really only want certain order lines.
How do I do this?
Orders and OrderList are both POCO entities generated by L2E and the poco entity generator.

You can manually join them:
Orders[] orderlist = (from m in db.Orders
join p in db.Orderlines
on p.OrderId = m.Id
where areas.Contains(m.Area)
&& m.Branch == branch
&& (m.OrderStatus == "1" || m.OrderStatus == "4")
&& m.SpecialInstrs == string.Empty
&& (p.LineType == "1" || p.LineType == "7")
&& p.MBomFlag != "C"
select m).ToArray();

Related

Shortening loop to one QUERY in LINQ

Below is a piece of code that I do in a loop:
At the beginning, in the first query, I get a list of location IDs. The list can be long.
Ultimately, I need to find for which LocationId FamiliId > 0
I have it done in a loop but I would like to do it in one question. Is it possible and if so how?
var locationIds = context.TblUsersDistricts
.Where(d => d.UserId == userId && d.ValidityTo == null)
.Select(x => x.LocationId).ToList();
int familyId = 0;
foreach(var item in locationIds) {
familyId = (from I in context.TblInsuree
join F in imisContext.TblFamilies on I.FamilyId equals F.FamilyId
join V in imisContext.TblVillages on F.LocationId equals V.VillageId
join W in imisContext.TblWards on V.WardId equals W.WardId
join D in imisContext.TblDistricts on W.DistrictId equals D.DistrictId
where(I.Chfid == chfid &&
D.DistrictId == item &&
F.ValidityTo == null &&
I.ValidityTo == null &&
V.ValidityTo == null &&
W.ValidityTo == null &&
D.ValidityTo == null)
select F.FamilyId)
.FirstOrDefault();
if (familyId > 0) break;
};
It sounds like you want:
var familyId = (
from item in locationIds
from I in context.TblInsuree
// ... etc
&& D.ValidityTo == null)
select F.FamilyId)
.FirstOrDefault();
?

Predicate is not working in foreach loop

if (rowCount == 1)
{
query =
(from x in partJoinTableRepository.GetPartJoinQuery()
join y in partRepository.GetPartsQuery() on x.PartId equals y.Id
join z in partProductTypeReposiotry.GetPartProductTypesQuery() on x.PartId equals z.PartId
where y.IsSkipped == 0 && (y.IsDisabled != "Y" || y.IsDisabled == null) && z.CreatedDate == x.CreatedDate
&& x.CreatedDate == Convert.ToDateTime(fromDate) && cpaclassids.Contains(x.ProductTypeId.ToString())
select x).Cast<PartJoinTable>().AsQueryable();
predicate = PredicateBuilder.True(query);
}
else
{
query = query.Join(partJoinTableRepository.GetPartJoinQuery(), "PartID", "PartID", "inner", "row1", null).Cast<PartJoinTable>().AsQueryable();
// predicate = PredicateBuilder.True(query);
} //query contains multiple dynamic inner joins
//repids contains the list ,I used the predicate builder for the linq to create AND Queries
foreach(var item in repids)
{
predicate = PredicateBuilder.True(query);
if (typeid == "3")
{
predicate = predicate.And(z => ids.Contains(z.ProductTypeId.ToString()) &&
z.CreatedDate == Convert.ToDateTime(fromDate));
}
}
var count = query.Where(predicate).Distinct().Count();
Here Predicate is not appended with more than one And condition. It is taking the last And Condition and the other And conditions are eliminated.
You are overwriting your predicate each loop.
This should work
predicate = PredicateBuilder.True(query);
foreach(var item in repids)
{
if (typeid == "3")
{
predicate = predicate.And(z => ids.Contains(z.ProductTypeId.ToString()) &&
z.CreatedDate == Convert.ToDateTime(fromDate));
}

Issue with LINQ IN clause when filter value is empty but works with filter values

I have a filter called serviceEntryFilter with a property System which could have values for instance EP1, EP2 OR EP1 and sometimes this filter would be null. If there are multiple values or a single value then the query (IN) clause runs fine . If the filter value is null then I get the following error:
Unable to create a constant value of type 'System.String[]'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
[HttpPost]
public ActionResult List(string ServiceEntryStatus, string ServiceEntryReconciled, string ServiceEntryReliabilityRecord, string ActiveServiceEntry,
int PageNo, ServiceEntryFilter serviceEntryFilter = null)
{
string[] systems = null;
var list = (from se in db.ServiceEntry
join r in db.RunLogEntry on se.RunLogEntryID equals r.ID into joinRunLogEntry
from r2 in joinRunLogEntry.DefaultIfEmpty()
join u in db.User on se.TechnicianID equals u.ID
join s in db.System1 on se.SystemID equals s.ID
where (
((se.RunLogEntryID == 0 || se.RunLogEntryID != null))
&& ((serviceEntryFilter.ID.HasValue == false) || (se.ID == serviceEntryFilter.ID.Value && serviceEntryFilter.ID.HasValue == true))
&& ((serviceEntryFilter.ServiceDateTime.HasValue == false) || (EntityFunctions.TruncateTime(se.ServiceDateTime) == EntityFunctions.TruncateTime(serviceEntryFilter.ServiceDateTime) && serviceEntryFilter.ServiceDateTime.HasValue == true))
&& ((serviceEntryFilter.RunDate.HasValue == false) || (EntityFunctions.TruncateTime(r2.RunDate) == EntityFunctions.TruncateTime(serviceEntryFilter.RunDate) && serviceEntryFilter.RunDate.HasValue == true))
&& ((serviceEntryFilter.Technician == null) || (u.FullName.Contains(serviceEntryFilter.Technician.Trim()) && serviceEntryFilter.Technician != null))
&& (
((ServiceEntryStatus == "O" && se.ServiceRequestClosed == false) ||
(ServiceEntryStatus == "C" && se.ServiceRequestClosed == true) ||
(ServiceEntryStatus == "A")
)
)
&& (
((ServiceEntryReliabilityRecord == null) ||
(ServiceEntryReliabilityRecord == "N" && se.ReliabilityRecord == false) ||
(ServiceEntryReliabilityRecord == "Y" && se.ReliabilityRecord == true) ||
(ServiceEntryReliabilityRecord == "A")
)
)
&& (
((ServiceEntryReconciled == null) ||
(ServiceEntryReconciled == "N" && se.Reconciled == false) ||
(ServiceEntryReconciled == "Y" && se.Reconciled == true) ||
(ServiceEntryReconciled == "A")
)
)
&& (
((ActiveServiceEntry == null) ||
(ActiveServiceEntry == "N" && se.Active == false) ||
(ActiveServiceEntry == "Y" && se.Active == true) ||
(ActiveServiceEntry == "A")
)
)
&& (
(s.PlatformID == platformID) || (platformID == 0)
)
&& ((serviceEntryFilter.System == null) || ((serviceEntryFilter.System != null) && systems.Contains(s.SystemFullName)))
)
orderby se.ID descending
select new ServiceSearchEntry()
{
ID = se.ID,
ServiceDateTime = se.ServiceDateTime,
Technician = u.FullName,
System = s.SystemFullName,
ReasonForFailure = se.ReasonForFailure,
RunDate = (r2 == null ? (DateTime?)null : r2.RunDate)
});
var listData = list.Skip((page - 1) * PageSize).Take(PageSize);
ServiceEntriesListViewModel viewModel = new ServiceEntriesListViewModel()
{
ServiceSearchEntry = listData,
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = list.Count()
}
};
}
The Issue:
The following clause is throwing an error when SystemFilter.System is NULL. It is null at times when users do not select values for it. Sample values are as follows:
EP1, EP2
EP1
TP2, TP3, TP4
&& ((serviceEntryFilter.System == null) || ((serviceEntryFilter.System != null) && systems.Contains(s.SystemFullName)))
If it has a value, then I put it in an array and its works like a charm, its just when its null.
The issue is that everything inside a LINQ statement will get translated to SQL. There isn't really a conditional statement that I see here that says "don't try to add this array filter if it's actually null".
I would initialize the systems array to a zero length array, overwrite it if the filter.Systems is not null, and then make my linq statement as follows:
systems.Contains(s.SystemFullName)
Don't include that null checking inside the LINQ statement as it's not doing what you are expecting.
To build conditional LINQ statements, you might want to look at PredicateBuilder: http://www.albahari.com/nutshell/predicatebuilder.aspx
This is a known limitation with Linq to Entities - see section on Referencing Non-Scalar Variables Not Supported.
In otherwords, this line:
systems.Contains(s.SystemFullName)
can't be used as part of your EF query.

How can i use select to string in linq?

How cani use below codes string id = ( from in .....) how?
using (StockProcedureDataContext stock = new StockProcedureDataContext())
{
id = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m.id);
How can i do above wthout using below?
id = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m).ToList()[0].id;
query.Single()
That's it.
id = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m.id).FirstOrDefault();
if you want to retrieve a single result user FirstOrDefault() or First().
If you use First() and the result is null.It will throws exception but not in FirstOrDefault().
var query = (from m in stock.StockTools
from ss in stock.RefStockStatus
where (m.statusid == 3 || m.statusid == 5) &&
ss.id == m.statusid && m.id == ItemID
select m.id).FirstOrDefault();
Just for variety...
query.Take(1)

LINQ query returns way more results than in the entire database

I have the following LINQ query. The problem is it's returning 13k results when tblSurveys only has 20 total. What am I doing wrong?
from s in surveyContext.tblSurveys
from st in surveyContext.tblTypes_for_Surveys
from t in surveyContext.tblSurvey_Types
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
(s.Unsubstantiated ||
(st.SurveyID == s.SurveyID && st.SurveyTypeID == t.SurveyTypeID &&
t.UnsubstantiatedAvailable && (from d in surveyContext.tblDeficiencies
where d.SurveyID == s.SurveyID
select d.DeficiencyID).Count() == 0))
orderby s.Survey_Date
select s;
I can see a cross join in there, look at the <-------
from s in surveyContext.tblSurveys
from st in surveyContext.tblTypes_for_Surveys
from t in surveyContext.tblSurvey_Types
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
(s.Unsubstantiated || <-------
(st.SurveyID == s.SurveyID && st.SurveyTypeID == t.SurveyTypeID &&
t.UnsubstantiatedAvailable && (from d in surveyContext.tblDeficiencies
where d.SurveyID == s.SurveyID
select d.DeficiencyID).Count() == 0))
orderby s.Survey_Date
select s;
it seem you need to do a left join in here
Do you have foreign keys and relationships setup in your database? If so, you can greatly simplify your query. I'd also recommend renaming your tables in the .dbml file so they aren't all prefixed with 'tbl'.
If you do have relationships setup, your query could look (something) like this:
from s in surveyContext.tblSurveys
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
(s.Unsubstantiated ||
(s.tblTypes_for_Surveys.Any(st => st.tblSurvey_Type.UnsubstantiatedAvailable) && s.tblDeficiencies.Count() == 0))
orderby s.Survey_Date
select s;

Categories