C# Linq to SQL Query between 2 Dates nos getting results - c#

I'm building a complex search query using Textboxes, Comboboxes and DateTimePicker.
For the Textbox and Combobox, the queries are working fine, but when add a datetimepicker for query between 2 dates, I'm getting nothing...
Using EF6 with LINQ...
So, my class to store data:
public class Projetos
{
public int ID { get; set; }
public string Conc { get; set; } //Combobox
public string Ent { get; set; } //Combobox
public string Def { get; set; } //Textbox
public DateTime DataR { get; set; }
}
The first query and return results:
public IEnumerable<Proj> LoadProj()
{
var ctx = new JEntities();
var query = (from p in ctx.tblProjs.AsQueryable()
join c in ctx.tblConcs on p.ConcID equals c.ConcID
join e in ctx.tblEnts on p.EntID equals e.EntID
select new Proj
{
ID = p.ProjID,
Conc = c.NameConc,
Ent = e.NameEnt,
Def = p.DefP,
DataR = p.DataR
});
// The combination of these 3 controls works fine!
if (TxtDefP.TextLength > 0)
{
query = query.Where(s => s.DefP.Contains(TxtDefP.Text));
}
if(CmbCon.SelectedValue != null)
{
string SelectedValue = CmbConc.GetItemText(CmbConc.SelectedItem);
query = query.Where(s => s.Conc == SelectedValue);
}
if(CmbEnt.SelectedValue != null)
{
string SelectedValue = CmbEnt.GetItemText(CmbEnt.SelectedItem);
query = query.Where(s => s.Ent == SelectedValue);
}
//When filtering between these 2 dates, I get no results
if (DataRFrom.Checked && DataRTo.Checked)
{
DateTime begin = DataRFrom.Value.Date;
DateTime end = DataRTo.Value.Date;
query = query.Where(s => s.DataR > begin && s.DataR < end);
}
return query.ToList();
}
In the SQL, I have dates like this... Perhaps the Date format in SQL are messing up all this???
My questions is, why can't I get any results between 2018-06-01 and 2018-06-06 since records with this date range are in Database?
Thanks.

Date property is missing:
query = query.Where(s => s.DataR.Date > begin && s.DataR.Date < end);

Related

How to convert this sql to efcore linq

Original data sheet:
SQL that can get the result you want:
select group_number,count(group_number) as group_count,receive_date
from hS_HZXX
where type = '1'
group by group_number,receive_date;
use ef core linq like this:
var hAATGroups = from p in dbContext.Set<HS_HZXX>()
where p.type == "1"
group p by new { Group_number = p.group_number, Sampling_date = p.sampling_date } into dto
select new DTO_HAATGroup
{
Group_number = dto.Key.Group_number,
HAAT_count = dto.Key.Group_number.Count(),
Sampling_date = dto.Key.Sampling_date.ToString("yyyy-MM-dd")
};
The DTO_HAATGroup:
public class DTO_HAATGroup
{
public string Group_number { get; set; }
public int HAAT_count { set; get; }
public string Sampling_date { get; set; }
}
The result of executing linq:
But I got the wrong result. . . Can you help me? How can I convert this SQL into a correct Linq statement.
I have solved this problem, the correct Linq writing is as follows:
var hAATGroups = from p in dbContext.Set<HS_HZXX>()
where p.type == "1"
group p by new { Group_number = p.group_number, Receive_date = p.receive_date } into dto
select new DTO_HAATGroup
{
Group_number = dto.Key.Group_number,
HAAT_count = dto.Count(),
Receive_date = dto.Key.Receive_date.ToString("yyyy-MM-dd")
};

{"error":"Explicit construction of entity type '###' in query is not allowed."}

I am new to LINQ, and i am getting this error message :
{"error":"Explicit construction of entity type 'Proj.Models.Ad' in
query is not allowed."}
I am using this code to retrieve the data
public ActionResult favads()
{
bool isValid = false;
string authToken = "";
if (Request["dt"] != null)
authToken = Request["dt"].ToString().Trim();
else
return Content("{\"error\":\"Please send device token parameter 'dt'.\"}", "application/json");
string message = (new CommonFunction()).ValidateToken(authToken, out isValid);
if (isValid)
{
long userID = 0;
if (Request["userID"] != null)
long.TryParse(Request["userID"].ToString().Trim(), out userID);
else
return Content("{\"error\":\"Please send user id parameter 'userID'.\"}", "application/json");
if (userID < 1)
return Content("{\"error\":\"Please select appropriate user to view details.\"}", "application/json");
try
{
var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) && Favtb.StatusID.Equals(1)).Select(p => new Ad() { ID = p.AdID.Value, CategoryID = int.Parse(p.CategoryID.ToString()) })
from c in db.Ads.Where(Adstb => Adstb.ID == d.ID).DefaultIfEmpty()
select new
{
FavId = d.ID,
c.ID,
c.Category.ParentCategoryID,
c.Category.CategoryID,
c.Category.LogoFile,
c.Category.CatName,
c.AdTitle,
AdDescription = (c.AdDescription.Length > 50 ? c.AdDescription.Substring(0, 50) : c.AdDescription),
c.CityID,
c.Price,
c.CreationDate,
c.Photos,
c.VideoUrl,
c.IsMobileVisibile
};
int pg = 0;
if (Request["p"] != null)
int.TryParse(Request["p"], out pg);
string _sortby = "MRF";
if (Request["sortby"] != null)
_sortby = Request["sortby"];
if (_sortby.Equals("OF"))
q = q.OrderBy(ad => ad.CreationDate.Value);
else if (_sortby.Equals("PD"))
q = q.OrderByDescending(ad => ad.Price.Value);
else if (_sortby.Equals("PA"))
q = q.OrderBy(ad => ad.Price.Value);
else
q = q.OrderByDescending(ad => ad.CreationDate.Value);
return Json(q.ToList().Skip(pg * recordsPerPage).Take(recordsPerPage), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Content("{\"error\":\"" + ex.Message + "\"}", "application/json");
}
}
else
{
return Content("{\"error\":\"" + message + "\"}", "application/json");
}
}
Ads class
public class Ads : Ad
{
public long ID { get; set; }
public string FashionType { get; set; }
public string ForRentSale { get; set; }
public string ForJobHire { get; set; }
public string JobTypeID { get; set; }
}
Ad is also mapped and you cannot project a new instance of it like this in a query. See this question.
What you can do is just create an anonymous type or even better in this case, since in your query you only use the ID of the Ad object retrieve just that:
var q = from d in db.AdsFavourites.Where(Favtb => Favtb.CreatedBy.Equals(userID) &&
Favtb.StatusID.Equals(1))
.Select(p => p.AdID.Value)
from c in db.Ads.Where(Adstb => Adstb.ID == d).DefaultIfEmpty()
select new
{
FavId = d,
c.ID,
c.Category.ParentCategoryID,
/* ... */
};
I recommend you look into Navigation Properties. I think it will make this query look neater
Also maybe look at this option instead of using the Method Syntax for the first table, might be more readable:
var q = from d in db.AdsFavourites
//In this case also no need for `Equals` - you are comparing value types
where d.CreateBy == userID && d.StatusID == 1
from c in db.Ads.Where(Adstb => Adstb.ID == d.AdID.Value).DefaultIfEmpty()
select new
{
FavId = d.AdID.Value,
c.ID,
/* ... */
};

ASP.NET MVC 5 Entity Join

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.

How to distinct by multiple columns with input parameter in Linq

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.

List based on variable from two tables

My program is a task program of sorts. What I'd like to do is construct a UI for a user/employee to see tasks they have to do on the given day the log in.
I have two tables, PostOne and PostEig, in a 1-M.
PostOne is the master table that contains the information about a single task.
PostEig is a table of users that are assigned to a task in Post One.
The models [simplified]
public class PostOne
{
public string One { get; set; }
[Key]
public string Two { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime ThrD { get; set; }
}
public class PostEig
{
public string EigOne { get; set; }
public string EigTwo { get; set; } //foreign key
[Key]
public string EigID { get; set; }
[Required]
public string EigA { get; set; } //user login
}
I'm having trouble with the controller. I'm not even sure how to start on the code necessary to achieve my goal, so I'm going to try to write it out:
call a list of PostEigs Where EigA == User.Identity.Name
and from this list.. call a list of PostOnes Where Two == EigTwo
and from this list.. call a list of PostOnes Where ThrD == DateTime.UtcNow.Date
I did try something like this:
public ActionResult SkedList()
{
return View(db.PostEigs.Where(m =>
m.EigA == User.Identity.Name ||
m.EigTwo == db.PostOnes.Where(o => o.ThrD == DateTime.UtcNow.Date)
).ToList());
}
If this is unclear, please let me know. I appreciate any advice or solutions, even if in a different direction.
Sounds like this is a candidate for an Inner Join. I find it's much easier to think in terms of SQL then transform it into LINQ.
SQL Query:
SELECT
po.*
FROM
PostOnes po
INNER JOIN
PostEig pe
ON
pe.EigTwo = po.Two
WHERE
pe.EigA = AUTH_NAME AND po.ThrD = TODAY()
C# LINQ Query:
var DB_PostEig = new List<PostEig>()
{
new PostEig(){EigTwo = "Foo1", EigA = "Foo"},
new PostEig(){EigTwo = "Foo2", EigA = "Foo"},
new PostEig(){EigTwo = "Bar1", EigA = "Bar"},
new PostEig(){EigTwo = "Bar2", EigA = "Bar"}
};
var DB_PostOnes = new List<PostOne>()
{
new PostOne(){Two = "Foo1", ThrD = new DateTime(1900,1,1)},
new PostOne(){Two = "Foo2", ThrD = new DateTime(2000,1,1)},
new PostOne(){Two = "Foo3", ThrD = new DateTime(1900,1,1)},
new PostOne(){Two = "Bar1", ThrD = new DateTime(1900,1,1)},
new PostOne(){Two = "Bar2", ThrD = new DateTime(1900,1,1)}
};
var authName = "Foo";
var currentDate = new DateTime(1900,1,1);
//Not sure if this is the most optimal LINQ Query, but it seems to work.
var queryReturn = DB_PostOnes.Join(DB_PostEig.Where(x => x.EigA == authName), x => x.Two, y => y.EigTwo, (x, y) => x)
.Where(z => z.ThrD == currentDate)
.ToList();
queryReturn.ForEach(x => Console.WriteLine(x.Two + " - " + x.ThrD)); //Foo1 - 1/1/1900
Edit:
LINQ Query without a join
var queryTwo = DB_PostOnes
.Where(x => DB_PostEig.Any(y => y.EigTwo == x.Two && y.EigA == authName) && x.ThrD == currentDate)
.ToList();

Categories