Problems with Linq(join) - asp.net-mvc-3

I am writting a query with linq(follow code bellow). I am looking for data from db.imovel and for each one bring a picture nested into db.fotoimovel. Keep in mind that I may have more than one picture for each db.imovel data.
The issue is when I run, it returns me all the pictures with the same db.imovel data in all of them.
It works for me if return the db.imovel data with just one(may be the first picture) from db.fotoimovel.
Code:
var retorno = (from c in db.fotoimovel
join p in db.imovel on c.idImovel equals p.idImovel
where p.MetragemImovel >= metragem1 && p.MetragemImovel <= metragem2 &&
p.StatusImovel == opcao &&
((String.IsNullOrEmpty(bairro)) || p.BairroImovel == bairro) &&
((imovel == null) || (p.TipoImovel == imovel)) &&
((carros == null) || (p.QtdVagaGaragemImovel == carros)) &&
((quartos == null) || (p.QtdQuartoImovel == quartos))
select new DadosImovel
{
Id = p.idImovel,
Titulo = p.TituloImovel,
Descricao = p.DescricaoImovel,
Foto = c.NomeFotoImovel,
TipoImovel = p.TipoImovel,
Endereco = p.EnderecoImovel,
Complemento = p.ComplementoImovel,
Bairro = p.BairroImovel,
Cidade = p.CidadeImovel,
Estado = p.EstadoImovel,
CEP = p.CEPImovel,
MetragemImovel = p.MetragemImovel,
QtdComodoImovel = p.QtdComodoImovel,
QtdQuartoImovel = p.QtdQuartoImovel,
QtdBanheiroImovel = p.QtdBanheiroImovel,
QtdVagaGaragemImovel = p.QtdVagaGaragemImovel,
QtdAndarImovel = p.QtdAndarImovel,
Status = p.StatusImovel,
Ativo = p.AtivoImovel
}).Distinct().ToList();

Related

How to optimize slow LINQ query?

I tried delete a statement that use contain() and use skip() take()
but it's still take a long time on execution
public JsonNetResult GetList(C.Lib.ListParam param, string type, DateTime? WorkDate, string MNo, string ANo, string AName, string Specifi, string PNo, string SName, string PType, string OrNo)
{
var idObj = (mis.Models.Security.CIdentity)Csla.ApplicationContext.User.Identity;
var c = new mis.Models.CEntities();
var targetList = (from obj in c.WorkOrders
join obj2 in c.Partners on obj.PartnerId equals obj2.PartnerId
join obj3 in c.Assets on obj.AssetsId equals obj3.AssetsId
join obj4 in c.WorkOrderItems on obj.WorkOrderId equals obj4.WorkOrderId
join obj5 in c.WorkItems on obj4.WorkId equals obj5.WorkId
join obj6 in c.Products on obj3.AssetsId equals obj6.AssetsId
where true && obj.TenantId == idObj.TenantId && obj2.Customer == true && obj.WorkOrderStatus <= 1
select new
{
WorkProgressId = obj.WorkOrderId,
OrderNo = obj.InOrderItem.OrderItem.Order.OrderNo,
ProductType = obj5.ProductType,
WorkOrderId = obj.WorkOrderId,
MakeQty = obj.MakeQty,//delete some column
PrepaidDate = obj.PrepaidDate,
CompleteDate = (from subobj in c.WorkOrderItems
where subobj.WorkOrderId == obj.WorkOrderId && subobj.CompleteDate != null
orderby subobj.CompleteDate descending, subobj.WorkItem.WorkNo descending
select subobj.CompleteDate).FirstOrDefault(),
WorkNoName = (from subobj in c.WorkOrderItems
where subobj.WorkOrderId == obj.WorkOrderId && subobj.CompleteDate != null
orderby subobj.WorkItem.WorkNo descending
select new { WorkNoName = subobj.WorkItem.WorkNo + " " + subobj.WorkItem.WorkName }).FirstOrDefault().WorkNoName,
});
targetList = targetList.GroupBy(x => x.MakeNo).Select(x => new
{
WorkProgressId = x.FirstOrDefault().WorkOrderId,
OrderNo = x.FirstOrDefault().OrderNo,
ProductType = x.FirstOrDefault().ProductType,
WorkOrderId = x.FirstOrDefault().WorkOrderId,
WorkOrderDate = x.FirstOrDefault().WorkOrderDate,
OrderQty = x.FirstOrDefault().OrderQty,
MakeQty = x.FirstOrDefault().MakeQty,
PrepaidDate = x.FirstOrDefault().PrepaidDate,//delete some column
CompleteDate = x.FirstOrDefault().CompleteDate,
WorkNoName = x.FirstOrDefault().WorkNoName
}).OrderByDescending(x => x.WorkOrderDate).ThenByDescending(x => x.WorkNoName);
param.SetCount(targetList);
targetList.OrderByDescending(x => x.WorkOrderDate).ThenByDescending(x=> x.WorkNoName);
var tk= targetList.Skip((param.Page - 1) * param.Rows).Take(param.Rows);
return JsonNetHelper.ReturnData(param,tk);
}
I'm wondering what is the best way to optimize it? Or would the query profiler do that for me?

"invalidcastexception specified cast is not valid linq" exeception in LINQ query

var Player = from PSI in regConfig.Player_SeasonalInfos
from PPI in regConfig.Player_PermanentInfos
where PSI.PaymentId == PlayerPayment.PaymentId
&& PPI.PlayerId == PSI.PlayerId
select new {
PlayerIds = string.Join(",", PSI.PlayerId),
PlayerSeasonalId = PSI.PlayerSeasonalId,
CityId = PPI.CityId
};
foreach (var item in Player)
{
Player_SeasonalInfo PlayerSeasonalInfos =
(from PSI in regConfig.Player_SeasonalInfos
where PSI.PlayerSeasonalId ==item.PlayerSeasonalId
select PSI).FirstOrDefault();
PlayerSeasonalInfos.StatusId = item.CityId == 1 ? 1 : 2;
regConfig.SubmitChanges();
}
i have write this code but i am getting excepiton"invalidcastexception specified cast is not valid linq" on line"
from PSI in regConfig.Player_SeasonalInfos
where PSI.PlayerSeasonalId ==item.PlayerSeasonalId
select PSI"
please suggest.

linq combine results from two tables to one select new statment?

With the following query how to I change that I dont have two sets of fields in the select new I want the information going into one set of columns not having two and a type field to say if its a traineeevent or a cpd event ?
List<EmployeeCPDReportRecord> employeeCPDRecords = new List<EmployeeCPDReportRecord>();
string employeeName;
var q = from cpd in pamsEntities.EmployeeCPDs
from traineeEvent in pamsEntities.TrainingEventTrainees
join Employee e in pamsEntities.Employees on cpd.EmployeeID equals e.emp_no
join TrainingEventPart tEventPart in pamsEntities.TrainingEventParts on traineeEvent.TrainingEventPartId equals tEventPart.RecordId
where (cpd.EmployeeID == id) && (startDate >= cpd.StartDate && endDate <= cpd.EndDate) &&
(traineeEvent.EmployeeId == id)
&& (traineeEvent.TraineeStatus == 1 || traineeEvent.TraineeStatus == 2)
&& (tEventPart.CPDHours > 0 || tEventPart.CPDPoints > 0)
&& (cpd.CPDHours > 0 || cpd.CPDPoints > 0)
|| traineeEvent.StartDate >= startDate
|| traineeEvent.EndDate <= endDate
orderby cpd.StartDate
select new
{
surname = e.surname,
forname1 = e.forename1,
forname2 = e.forename2,
EmployeeID = cpd.EmployeeID,
StartDate = cpd.StartDate,
EndDate = cpd.EndDate,
CPDHours = cpd.CPDHours,
CPDPoints = cpd.CPDPoints,
Description = cpd.Description,
TrainingStartDate = tEventPart.StartDate,
TrainingEndDate = tEventPart.EndDate,
TrainingCPDHours = tEventPart.CPDHours,
TrainingCPDPoints = tEventPart.CPDPoints,
TrainingEventDescription = tEventPart.Description
};
if (q != null)
{
Array.ForEach(q.ToArray(), i =>
{
if (ContextBase.encryptionEnabled)
employeeName = ContextBase.Decrypt(i.surname) + ", " + ContextBase.Decrypt(i.forname1) + " " + ContextBase.Decrypt(i.forname2);
else
employeeName = i.surname + ", " + i.forname1 + " " + i.forname2;
if (i.TrainingStartDate != new DateTime(1900, 1, 1))
employeeCPDRecords.Add(new EmployeeCPDReportRecord(employeeName, Convert.ToDateTime(i.StartDate), Convert.ToDateTime(i.EndDate), Convert.ToDecimal(i.CPDHours), Convert.ToDecimal(i.CPDPoints), i.Description,i.t,i.EndDate,Convert.ToDecimal(i.CPDHours),Convert.ToDecimal(i.CPDPoints),i.Description,"L&D"));
else
employeeCPDRecords.Add(new EmployeeCPDReportRecord(employeeName, Convert.ToDateTime(i.StartDate), Convert.ToDateTime(i.EndDate), Convert.ToDecimal(i.CPDHours), Convert.ToDecimal(i.CPDPoints), i.Description, i.StartDate, i.EndDate, Convert.ToDecimal(i.CPDHours), Convert.ToDecimal(i.CPDPoints), i.Description, "Employee CPD"));
});
}
Use this code
List<EmployeeCPDReportRecord> employeeCPDRecords = new List<EmployeeCPDReportRecord>();
var q = ( from cpd in pamsEntities.EmployeeCPDs
from traineeEvent in pamsEntities.TrainingEventTrainees
join Employee e in pamsEntities.Employees on cpd.EmployeeID equals e.emp_no
join TrainingEventPart tEventPart in pamsEntities.TrainingEventParts on traineeEvent.TrainingEventPartId equals tEventPart.RecordId
where (cpd.EmployeeID == id) && (startDate >= cpd.StartDate && endDate <= cpd.EndDate) &&
(traineeEvent.EmployeeId == id)
&& (traineeEvent.TraineeStatus == 1 || traineeEvent.TraineeStatus == 2)
&& (tEventPart.CPDHours > 0 || tEventPart.CPDPoints > 0)
&& (cpd.CPDHours > 0 || cpd.CPDPoints > 0)
|| traineeEvent.StartDate >= startDate
|| traineeEvent.EndDate <= endDate
orderby cpd.StartDate
select new EmployeeCPDReportRecord
{
YourEmployeColumnName=(ContextBase.encryptionEnabled==true?ContextBase.Decrypt(e.surname) + ", " + ContextBase.Decrypt(e.forname1) + " " + ContextBase.Decrypt(e.forname2):e.surname + ", " + e.forname1 + " " + e.forname2),
YourEmployeeCPDColumnName=(i.TrainingStartDate !=new DateTime(1900, 1, 1)?"L&D":"Employee CPD")
surname = e.surname,
forname1 = e.forename1,
forname2 = e.forename2,
EmployeeID = cpd.EmployeeID,
StartDate = cpd.StartDate,
EndDate = cpd.EndDate,
CPDHours = cpd.CPDHours,
CPDPoints = cpd.CPDPoints,
Description = cpd.Description,
TrainingStartDate = tEventPart.StartDate,
TrainingEndDate = tEventPart.EndDate,
TrainingCPDHours = tEventPart.CPDHours,
TrainingCPDPoints = tEventPart.CPDPoints,
TrainingEventDescription = tEventPart.Description
}).ToList<EmployeeCPDReportRecord>();

Dynamic linq not working

I have a problem. I want to build a dynamic LINQ query like this:
var result = from li in datacTx.LIs
where
(((StartDate != null) && (StartDate.Date != DateTime.MinValue)) ? li.Available <= StartDate.Date : true) &&
(((EndDate != null) && (EndDate.Date != DateTime.MinValue)) ? li.Expire <= EndDate.Date : true)
select new
{
A,
B,
C,
D
};
Before calling this query I am intializing the StartDate and EndDate with:
StartDate = DateTime.MinValue;
EndDate = DateTime.MinValue;
The problem is that the branch of "if" is always wrong I never can get the "true" branch if the StartDate and EndDate are having MinValue.
Try using a simpler condition:
where ((StartDate == DateTime.MinValue || li.Available <= StartDate.Date) &&
(EndDate == DateTime.MinValue || li.Expire <= EndDate))
However, if I were to implement something like this, I would actually create the query dynamically:
var query = datacTx.LIs;
if(StartDate != DateTime.MinValue)
query = query.Where(li => li.Available <= StartDate.Date);
if(EndDate != DateTime.MinValue)
query = query.Where(li => li.Expire <= EndDate .Date);
var result = query.Select(x => new { A, B, C, D });

Converting a Query to LINQ

How can I convert the following query in a Linq with Lambda ?
SELECT DISTINCT Registro, COUNT(Registro) as qnt
FROM XML_Relatorio
WHERE Arquivo = 'redenet.xml'
AND TipoErro <> 'Imovel Inserido'
AND TipoErro <> 'TI'
AND DataHora BETWEEN '01-01-2012' AND '02-01-2012'
GROUP BY Registro
ORDER BY Registro
I'm trying the following code, but I need some help to build the LINQ with Lambda
IQueryable<XML_Relatorio> quantidadeErro = db.XML_Relatorios
.Where(a => a.Arquivo == "redenet.xml"
&& a.TipoErro != "Imovel Inserido"
&& a.TipoErro != "TI");
Supposing the DataHora field is of Date or DateTime type.
// parse the strings to datetime
var start = DateTime.Parse("01-01-2012");
var end = DateTime.Parse("02-01-2012");
IQueryable<XML_Relatorio> quantidadeErro = db.XML_Relatorios
.Where(a => a.Arquivo == "redenet.xml"
&& a.TipoErro != "Imovel Inserido"
&& a.TipoErro != "TI"
// and compare them...
&& a.DataHora > start && a.DataHora < end);

Resources