I have the following SQL query
Select cLedgerName,dDateFrom,cPeriodType,nPeriodFrom,nPeriodTo
from sys_Account_Ledger a,sys_Log_Deposits_Interest_Master b
where a.cGLCode=b.cGLCode and b.dDateFrom='08-11-2012' and b.cPeriodType='Days'
I wanted to write this query using Lambda expression.This is where I am stuck.
public IList<ListViewData> GetDepositsListViewData(string glCode, string effectDate, string periodType)
{
using (var db = new DataClasses1DataContext())
{
var data=db.sys_Account_Ledgers.Join(db.sys_Log_Deposits_Interest_Masters,
ledger=>ledger.cGLCode,
deposits=>deposits.cGLCode,
(ledger,deposits)=>new {db.sys_Account_Ledgers =ledger,db.sys_Log_Deposits_Interest_Masters =deposits})
}
}
I have created a class which will be the return type of my query.
Here is the class
public class ListViewData
{
public string LedgerName { get; set; }
public string DateFrom { get; set; }
public string PeriodType { get; set; }
public int PeriodFrom { get; set; }
public int PeriodTo { get; set; }
}
Can anyone help me out with the lambda expression?
var result = dataContext.SysAccountLedger
.Join(dataContext.SysLogDepositsInterestMaster,
a => a.cGlCode,
b => b.cGlCode,
(a, b) => new ListViewData
{
LedgerName = a.LedgerName,
DateFrom = b.DateFrom,
PeriodType = b.PeriodType
// other properties
})
.Where(item => item.DateFrom = Convert.ToDateTime("08-11-2012") &&
item.PeriodType == "Days")
.ToList();
//Direct translation into Linq:
var query = from a in db.sys_Account_Ledger
join b in db.sys_Log_Deposits_Interest_Master on a.cGLCode equals b.cGLCode
where b.dDateFrom == Convert.ToDateTime("08-11-2012") && b.cPeriodType == "Days"
select new { a, b };
//Lambda of this:
var query = db.sys_AccountLedger
.Join(db.sys_Log_Deposits_Interest_Master,
a => a.cGLCode,
b => b.cGLCode,
(a, b) => new {a , b})
.Where(w => w.dDateFrom == Convert.ToDateTime("08-11-2012") && w.cPeriodType == "Days");
Related
I have this table:
PL_ProjectLikes
PC_ProjectConnect
PR_ProjectRating
P_Project
PL_PageLayout
This is my link query:
List<PProject> p = ctx.PProject.Where(x => x.PCountryCode == cC && x.PParentalGuidence == r).ToList();
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
Now PL_PageLayout has a field called PL_P_Id or PlPId, this is a guid.
What i want is to take theses tables figure out a rating or sum or count to pull the best projects to be filtered at the top of the list.
What i have done to extract each of these tables by grouping them with the PIdG which is a guid and is liked to each of the tables from the project and each project is a PL_PageLayout.
Extracted values from the tables:
PL_ProjectLIke:
var plike = ctx.PlProjectLike.Where(x => x.PlValue == "Like").Select(c => c).GroupBy(g => new { g.PlPIdG }, (key, group) => new { sumR = group.Count(), pidG = key.PlPIdG });
List<string> p0p = plike.Select(t => t.pidG).ToList();
PR_ProjectRating:
var prating = ctx.PrProjectRating.Where(x => x.PrIsDeleted == false).Select(k => k).GroupBy(g => new { g.PrPIdG }, (key, group) => new { sumR = group.Sum(k => k.PrValue), pidG = key.PrPIdG });
List<string> p0 = prating.Select(t => t.pidG).ToList();
PC_ProjectConnect:
var pconnect = ctx.PcProjectConnect.Where(x => x.PcStatus == "Connected").Select(c => c).GroupBy(g => new { g.PcPIdG }, (key, group) => new { sumR = group.Count(), pidG = key.PcPIdG });
List<string> p0pp = pconnect.Select(t => t.pidG).ToList();
How do i combine these filters above to find the best projects or pagelayouts using linq?
I tried this:
pppp = pppp.OrderBy(c => p0.Contains(c.PlPId) ? p0.IndexOf(c.PlPId) : int.MaxValue).ToList();
Which works and gets the best projects by the sum of the ratings for each project, but how do i combine the other two querys to find the best project?
Would this be the answer or would this just get the query of the last set:
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
pppp = pppp.OrderBy(c => p0.Contains(c.PlPId) ? p0.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0p.Contains(c.PlPId) ? p0p.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0pp.Contains(c.PlPId) ? p0p.IndexOf(c.PlPId) : int.MaxValue).ToList();
Every time im liking a project as im testing its pushing the project down the list so that bit of code above is not working but making some progress
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
pppp = pppp.OrderBy(c => p0.Contains(c.PlPId) ? p0.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0p.Contains(c.PlPId) ? p0p.IndexOf(c.PlPId) : int.MaxValue).ToList();
pppp = pppp.OrderBy(c => p0pp.Contains(c.PlPId) ? **p0pp**.IndexOf(c.PlPId) : int.MaxValue).ToList();
I have put some test code together at RexTester but I am not sure of your question. I think you can just order the result lists as they are created, or am I just misunderstanding the question
public class PlProjectLike
{
public int PlId { get; set; }
public Guid PlPIdG { get; set; }
public int PlUId { get; set; }
public string PlValue { get; set; }
public DateTime PlCreatedDate { get; set; }
}
public class PcProjectConnect
{
public int PcId { get; set; }
public Guid PcPIdG { get; set; }
public int PcUId { get; set; }
public DateTime PcCreatedDate { get; set; }
public string PcStatus{ get; set; }
}
public class PrProjectRating
{
public int PrId { get; set; }
public int PrUId { get; set; }
public string PrText { get; set; }
public int PrValue { get; set; }
public Guid PrPIdG { get; set; }
public DateTime PrCreatedDate { get; set; }
public bool PrIsDeleted{ get; set; }
}
public class PProject
{
public int PId { get; set; }
public Guid PIdG { get; set; }
public string PName { get; set; }
public DateTime PDateCreated { get; set; }
public bool PDeleted { get; set; }
public int PUId { get; set; }
public int PTtId { get; set; }
public string PCountry { get; set; }
public string PCountryCode { get; set; }
public string PParentalGuidence { get; set; }
public string PConnectionType { get; set; }
}
public class PlPageLayout
{
public int PLId { get; set; }
public Guid PlPId { get; set; }
public string PLName { get; set; }
}
public class CTX
{
public List<PProject> PProject { get; set; }
public List<PlPageLayout> PlPageLayout { get; set; }
public List<PlProjectLike> PlProjectLike { get; set; }
public List<PrProjectRating> PrProjectRating { get; set; }
public List<PcProjectConnect> PcProjectConnect { get; set; }
public CTX()
{
PProject = new List<PProject>();
PlPageLayout = new List<PlPageLayout>();
PlProjectLike = new List<PlProjectLike>();
PrProjectRating = new List<PrProjectRating>();
PcProjectConnect = new List<PcProjectConnect>();
}
}
public class LikeGroup
{
public int sumR { get; set; }
public Guid pidG { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
CTX ctx = new CTX();
String r = "R";
string cC = "us";
// Select project for country and rating
List<PProject> p = ctx.PProject.Where(x => x.PCountryCode == cC && x.PParentalGuidence == r).ToList();
// List of PlPageLayouts where the PlPId is in the selected PProject list
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
// List of Count/PlPIdG from PlProjectLike where the PlValue is 'Like' Ordered by the count descending
List<LikeGroup> plike = ctx.PlProjectLike.Where(x => x.PlValue == "Like").Select(c => c).GroupBy(g => new { g.PlPIdG }, (key, group) => new LikeGroup() { sumR = group.Count(), pidG = key.PlPIdG }).OrderByDescending(dat => dat.sumR).ToList();
// List of Sum(PrValue)/PlPIdG from PrProjectRating where PrIsDeleted is false Ordered by the Sum(PrValue) descending
List<LikeGroup> prating = ctx.PrProjectRating.Where(x => x.PrIsDeleted == false).Select(k => k).GroupBy(g => new { g.PrPIdG }, (key, group) => new LikeGroup(){ sumR = group.Sum(k => k.PrValue), pidG = key.PrPIdG }).OrderByDescending(dat => dat.sumR).ToList();
// List of Count/PlPIdG from PcProjectConnect where PcStatus is Connected Ordered by the count descending
List<LikeGroup> pconnect = ctx.PcProjectConnect.Where(x => x.PcStatus == "Connected").Select(c => c).GroupBy(g => new { g.PcPIdG }, (key, group) => new LikeGroup() { sumR = group.Count(), pidG = key.PcPIdG }).OrderByDescending(dat => dat.sumR).ToList();
List<PlProjectLike> OrderedProjectLikeList =
(from pl in ctx.PlProjectLike
join ord in plike on pl.PlPIdG equals ord.pidG
orderby ord.sumR descending
select pl).ToList();
List<PrProjectRating> OrderedPrProjectRatingList =
(from pr in ctx.PrProjectRating
join ord in prating on pr.PrPIdG equals ord.pidG
orderby ord.sumR descending
select pr).ToList();
List<PcProjectConnect> OrderedPcProjectConnectList =
(from pc in ctx.PcProjectConnect
join ord in prating on pc.PcPIdG equals ord.pidG
orderby ord.sumR descending
select pc).ToList();
}
}
From the help of this answer:
https://stackoverflow.com/questions/65014531/summing-a-value-inside-of-a-anonymous-type
I added the following code to get the best projects:
var ratings =
from r1 in ctx.PrProjectRating
where r1.PrIsDeleted == false
group r1.PrValue by r1.PrPIdG into g
select new
{
Id = g.Key,
Sum = g.Sum(),
};
var likes =
from l in ctx.PlProjectLike
where l.PlValue == "Like"
group 1 by l.PlPIdG into g
select new
{
Id = g.Key,
Count = g.Count(),
};
var connects =
from c1 in ctx.PcProjectConnect
where c1.PcStatus == "Connected"
group 1 by c1.PcPIdG into g
select new
{
Id = g.Key,
Count = g.Count(),
};
var ids = ratings.Select(r => r.Id)
.Union(likes.Select(l => l.Id))
.Union(connects.Select(c => c.Id))
.ToHashSet();
var query =
from i in ids
join ra in ratings on i equals ra.Id into rs
from ra in rs.DefaultIfEmpty()
join l in likes on i equals l.Id into ls
from l in ls.DefaultIfEmpty()
join co in connects on i equals co.Id into cs
from co in cs.DefaultIfEmpty()
select new
{
Id = i,
Ratings = ra?.Sum ?? 0,
Likes = l?.Count ?? 0,
Connects = co?.Count ?? 0,
};
List<PlPageLayout> pppp = ctx.PlPageLayout.Where(x => p.Select(n => n.PIdG).Contains(x.PlPId)).ToList();
pppp = query.OrderByDescending(x => x.Ratings + x.Likes + x.Connects).SelectMany(j => pppp.Where(s => s.PlPId == j.Id)).ToList();
I have a class which contains ProjectID and its detail as follows and I would like to retrieve the list detail from the SQL server. I am struggling to convert list of rows into ProjectModel.
I have tried below and referred various source but no luck. I want to write code for get list instead of BuildAutoCompleteList(PTO).
Should i need to use groupby to achieve the result.
Class
public class ProjectModel
{
public string ProjectName { get; set; }
public Guid ProjectID { get; set; }
public IEnumerable<SegmentModel> Segments { get; set; }
}
public class SegmentModel
{
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string MileStone { get; set; }
}
public class ProjectMilestone
{
public string ProjectName { get; set; }
public Guid ProjectID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string MileStone { get; set; }
public ProjectMilestone() { }
}
Entity
var collection = _db.GetReportMilestones().Join(_db.GetReports(), RM => RM.ReportId, R => R.Id,
(RM, R) => new { RM, R }).
Join(_db.GetProjects(), P => P.R.ProjectId, PR => PR.Id, (P, PR) => new { P, PR }).Where(M => M.P.R.StateId == 1)
.Select(PTO => new ProjectTimelineModel
{
ProjectName = PTO.PR.Name,
ProjectID = PTO.PR.Id,
Segments = BuildAutoCompleteList(PTO)
}).ToList();
Below is my attempt, which throws the error.
var collection = _db.GetReportMilestones().Join(_db.GetReports(), RM => RM.ReportId, R => R.Id,
(RM, R) => new { RM, R }).
Join(_db.GetProjects(), P => P.R.ProjectId, PR => PR.Id, (P, PR) => new { P, PR }).Where(M => M.P.R.StateId == 1)
.Select(PTO => new ProjectMilestone
{
ProjectName = PTO.PR.Name,
ProjectID = PTO.PR.Id,
StartDate = PTO.P.RM.ScheduledDate,
EndDate = PTO.P.RM.PassedDate,
MileStone = PTO.P.RM.Name
}).ToList();
var results = collection.OrderBy(n => n.ProjectName);
var groupbyResult = results.GroupBy(n => new { n.ProjectID, n.ProjectName }).Select(x => new ProjectTimelineModel()
{
ProjectID = x.Key.ProjectID,
ProjectName = x.Key.ProjectName,
Segments = x.GroupBy(n => n.ProjectID)
}).ToList();
I have code that works, but I worked around a 'Join' in Linq to Entities, because I could not figure it out.
Could you please show me how to succesfully apply it to my code?
My desired result is a dictionary:
Dictionary<string, SelectedCorffData> dataSelectedForDeletion = new Dictionary<string, SelectedCorffData>();
The above mentioned class:
public class SelectedCorffData
{
public long CorffId { get; set; }
public string ReportNumber { get; set; }
public DateTime CorffSubmittedDateTime { get; set; }
}
Please note the 'intersectResult' I am looping through is just a string collection.
Here is my code:
DateTime dateToCompare = DateTime.Now.Date;
Dictionary<string, SelectedCorffData> dataSelectedForDeletion = new Dictionary<string, SelectedCorffData>();
foreach (var mafId in intersectResult)
{
var corffIdsPerMaf = context
.Mafs
.Where(m => m.MafId == mafId)
.Select(m => m.CorffId);
var corffIdForMaf = context
.Corffs
.Where(c => corffIdsPerMaf.Contains(c.Id))
.OrderByDescending(c => c.CorffSubmittedDateTime)
.Select(c => c.Id)
.First();
//Selected close-out forms, whose MAF's may be up for deletion, based on date.
var corffData = context
.Corffs
.Where(c => c.Id == corffIdForMaf && System.Data.Entity.DbFunctions.AddYears(c.CorffSubmittedDateTime, 1).Value > dateToCompare)
.Select(c => new SelectedCorffData () { CorffId = c.Id, ReportNumber = c.ReportNumber, CorffSubmittedDateTime = c.CorffSubmittedDateTime })
.FirstOrDefault();
if(corffData != null)
{
dataSelectedForDeletion.Add(mafId, corffData);
}
}
Please note: this is not just a simple join. If it can't be simplified, please tell me. Also please explain why.
The code below I don't think is exactly right but it is close to what you need. I simulated the database so I could get the syntax correct.
namespace System
{
namespace Data
{
namespace Entity
{
public class DbFunctions
{
public static Data AddYears(DateTime submittedTime, int i)
{
return new Data();
}
public class Data
{
public int Value { get; set; }
}
}
}
}
}
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
Context context = new Context();
int dateToCompare = DateTime.Now.Year;
var corffIdsPerMaf = context.Mafs.Select(m => new { id = m.CorffId, mafs = m}).ToList();
var corffIdForMaf = context.Corffs
.Where(c => System.Data.Entity.DbFunctions.AddYears(c.CorffSubmittedDateTime, 1).Value > dateToCompare)
.OrderByDescending(c => c.CorffSubmittedDateTime).Select(c => new { id = c.Id, corff = c}).ToList();
var intersectResult = from p in corffIdsPerMaf
join f in corffIdForMaf on p.id equals f.id
select new SelectedCorffData() { CorffId = p.id, ReportNumber = f.corff.ReportNumber, CorffSubmittedDateTime = f.corff.CorffSubmittedDateTime };
Dictionary<string, SelectedCorffData> dataSelectedForDeletion = intersectResult.GroupBy(x => x.ReportNumber, y => y).ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
public class Context
{
public List<cMafs> Mafs { get; set;}
public List<cCorffs> Corffs { get; set;}
}
public class cMafs
{
public int CorffId { get; set; }
}
public class cCorffs
{
public DateTime CorffSubmittedDateTime { get; set; }
public int Id { get; set; }
public string ReportNumber { get; set; }
}
public class Test
{
}
public class SelectedCorffData
{
public long CorffId { get; set; }
public string ReportNumber { get; set; }
public DateTime CorffSubmittedDateTime { get; set; }
}
}
I'm new in ASP, Entity and lambda expressions. How can I join two tables?
Route Model:
public partial class Route
{
public Route()
{
Flights = new HashSet<Flight>();
}
public int RouteID { get; set; }
public int DepartureAirportID { get; set; }
public int ArrivalAirportID { get; set; }
public int FlightDuration { get; set; }
public virtual Airport Airport { get; set; }
public virtual Airport Airport1 { get; set; }
public virtual ICollection<Flight> Flights { get; set; }
}
Airport Model:
public partial class Airport
{
public Airport()
{
Routes = new HashSet<Route>();
Routes1 = new HashSet<Route>();
}
public int AirportID { get; set; }
public string City { get; set; }
public string Code { get; set; }
public virtual ICollection<Route> Routes { get; set; }
public virtual ICollection<Route> Routes1 { get; set; }
}
SQL query looks like this:
SELECT a.AirportID, a.City
FROM Route r INNER JOIN Airport a ON r.ArrivalAirportID = a.AirportID
WHERE r.DepartureAirportID = #departureAirportID
ORDER BY a.City
Sorry for this easy question but I don't know how to do this with Entity Framework...
Something like this should do (untested and just going on from your query) with a variable hard-coded):
using (var db = new YourDbContext())
{
var query = from r in db.Route
join a in db.Airport a on r.ArrivalAirportID equals a.AirportID
where r.DepartureAirportID = 1 // replace with your varialble.
orderby a.City
select a;
}
Include with join entity framework. here doctorSendAnswerModel also a inner table.
var data = _patientaskquestionRepository.Table.Include(x=>x.DoctorSendAnswer).Join(_patientRepository.Table, a => a.PatientId, d => d.Id, (a, d) => new { d = d, a = a }).Where(x => x.a.DoctorId == doctorid);
if(!string.IsNullOrEmpty(status))
data=data.Where(x=>x.a.Status==status);
var result = data.Select(x => new {x= x.a,y=x.d }).ToList();
var dt = result.Select(x => new PatientAskQuestionModel()
{
PatientId = x.x.PatientId.Value,
AskQuestion = x.x.AskQuestion,
Id = x.x.Id,
DoctorId = x.x.DoctorId,
FileAttachment1Url = x.x.FileAttachment1,
DocName = x.y.FirstName + " " + x.y.LastName,
CreatedDate = x.x.CreatedDate.Value,
doctorSendAnswerModel = x.x.DoctorSendAnswer.Select(t => new DoctorSendAnswerModel { Answer = t.Answer }).ToList()
}).ToList();
return dt;
LinQ query:
from r in context.Route
join a in context.Airport
on r.ArrivalAirportID equals a.AirportID
WHERE r.DepartureAirportID = "value"
ORDER BY a.City
select a.AirportID, a.City
var balance = (from a in context.Airport
join c in context.Route on a.ArrivalAirportID equals c.AirportID
where c.DepartureAirportID == #departureAirportID
select a.AirportID)
.SingleOrDefault();
You can do the following:
var matches = from a in context.Airports
join r in context.Routes
on a.AirportID equals r.ArrivalAirportID
where r.DepartureAirportID = departureAirportID
order by a.City
select new
{
a.AirportID,
a.City
};
Entity query with conditional join with pagination.
if (pageIndex <= 0)
pageIndex = 1;
pageIndex = ((pageIndex - 1) * pageSize) ;
var patient = _patientRepository.Table.Join(_DoctorPatient.Table.Where(x => x.DoctorId == Id && x.IsBlocked==false), x => x.Id, d => d.PatientId, (x, d) => new { x = x });
if (state != "")
patient = patient.Where(x => x.x.State.Contains(state));
if (name != "")
patient = patient.Where(x => (x.x.FirstName + x.x.LastName).Contains(name));
if (sdate != null)
patient = patient.Where(x => x.x.CreatedDate >= sdate);
if (eDate != null)
patient = patient.Where(x => x.x.CreatedDate <= eDate);
var result = patient.Select(x => x.x).Select(x => new PatientDoctorVM() { PatientId = x.Id, Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, SSN = x.NewSSNNo, UserProfileId = x.UserProfileId, Email = x.Email, TumbImagePath = x.TumbImagePath }).OrderBy(x => x.Id).Skip(pageIndex).Take(pageSize).ToList();
Your entity and lembda query will be lool like this:
return (from d in _doctorRepository.Table
join p in _patientDoctor.Table on d.Id equals p.DoctorId
where p.PatientId == patientid.Value select d
).ToList();
Take a look at this site, it will explain you how the join works in Linq.
So if you ever need it again you will be able to solve it yourself.
i have tre tables T020_CLIENTI,T021_SITI,T520_REL_STRUMENTI_SITI that i would join and then distinct by T020.Ragione_sociale,T520.DA_DATA,T520.A_DATA but obtain as return parameters T020.Ragione_sociale,T020.id_cliente,T520.cod_stumento,T520.DA_DATA,T520.A_DATA
my tables are
public partial class T020_CLIENTI
{
public decimal ID_CLIENTE { get; set; }
public Nullable<decimal> ID_COMUNE { get; set; }
public Nullable<decimal> ID_CONSORZIO { get; set; }
public string COD_LINEA_ATTIVITA { get; set; }
}
public partial class T021_SITI
{
public decimal ID_SITO { get; set; }
public Nullable<decimal> ID_FORNITORE { get; set; }
public Nullable<decimal> ID_CLIENTE { get; set; }
}
public partial class T520_REL_STRUMENTI_SITI
{
public string COD_STUMENTO { get; set; }
public decimal ID_SITO { get; set; }
public System.DateTime DA_DATA { get; set; }
public System.DateTime A_DATA { get; set; }
}
my linq query is
using (var cont = DALProvider.CreateEntityContext())
{
var query =
from cliente in cont.T020_CLIENTI
from sito
in cont.T021_SITI
.Where(s => s.ID_CLIENTE == cliente.ID_CLIENTE)
.DefaultIfEmpty()
from relStrumenti
in cont.T520_REL_STRUMENTI_SITI
.Where(s => s.ID_SITO == sito.ID_SITO)
.DefaultIfEmpty()
select new
{
clienteRec = cliente,
sitoRec = sito,
relStrumentiRec = relStrumenti
};
if (!string.IsNullOrEmpty(aiFiltro.RAGIONE_SOCIALE))
query = query.Where(i => i.clienteRec.RAGIONE_SOCIALE.ToUpper().Contains(aiFiltro.RAGIONE_SOCIALE.ToUpper()));
var vRes = (from clienteDef in query
select new ClienteFiltrato
{
RAGIONE_SOCIALE = clienteDef.clienteRec.RAGIONE_SOCIALE,
ID_CLIENTE = clienteDef.clienteRec.ID_CLIENTE,
COD_STRUMENTO = clienteDef.relStrumentiRec.COD_STUMENTO,
DATA_DA = clienteDef.relStrumentiRec.DA_DATA,
DATA_A = clienteDef.relStrumentiRec.A_DATA
}) ;
return vRes.AsQueryable();
}
but in my linq query i don't know where i can insert distinct and input parameter (:pPOD) to obtain my linq that in oracle query is:
SELECT DISTINCT t020.ragione_sociale,
da_data,
a_data,
t020.id_Cliente,
:pPOD
FROM t020_clienti t020, t021_siti t021, T520_REL_STRUMENTI_SITI t520
WHERE t020.id_cliente = t021.id_cliente
AND t021.id_sito = t520.id_sito
AND (:pPOD is null or t520.cod_stumento = :pPOD)
ORDER BY da_data
where :pPOD is an input parameter that i could have set or not.
Try to add (s.COD_STUMENTO == pPod || pPod == null) to your Where clause, where you are filtering T520_REL_STRUMENTI_SITI entity. pPod should be a string variable.
Please have in mind that if you are using DefaultIfEmpty() in LINQ this will be translated to left join in SQL.
Modified query follows:
string pPod = null;
using (var cont = DALProvider.CreateEntityContext())
{
var query =
(from cliente in cont.T020_CLIENTI
from sito
in cont.T021_SITI
.Where(s => s.ID_CLIENTE == cliente.ID_CLIENTE)
.DefaultIfEmpty()
from relStrumenti
in cont.T520_REL_STRUMENTI_SITI
.Where(s => s.ID_SITO == sito.ID_SITO && (s.COD_STUMENTO == pPod || pPod == null))
.DefaultIfEmpty()
select new
{
clienteRec = cliente.Distinct(),
sitoRec = sito,
relStrumentiRec = relStrumenti
});
if (!string.IsNullOrEmpty(aiFiltro.RAGIONE_SOCIALE))
query = query.Where(i => i.clienteRec.RAGIONE_SOCIALE.ToUpper().Contains(aiFiltro.RAGIONE_SOCIALE.ToUpper()));
var vRes = (from clienteDef in query
select new ClienteFiltrato
{
RAGIONE_SOCIALE = clienteDef.clienteRec.RAGIONE_SOCIALE,
ID_CLIENTE = clienteDef.clienteRec.ID_CLIENTE,
COD_STRUMENTO = clienteDef.relStrumentiRec.COD_STUMENTO,
DATA_DA = clienteDef.relStrumentiRec.DA_DATA,
DATA_A = clienteDef.relStrumentiRec.A_DATA
}).Distinct() ;
return vRes.AsQueryable();
}
You can use:
string query =
((System.Data.Objects.ObjectQuery)query).ToTraceString();
This will show you the generated SQL from LINQ Queryable object.