I have database table called Absence
, which has a column called ABSDate
. The type of this column is Datetime
.
I'm trying to use a LINQ query to search inside this table. When I use the Contains
method to query against other columns, I get results:
Working Query
dataGridView1.DataSource = (from A in context.Absence
join S in context.Stagiaire on A.STG equals S.ID
join G in context.Groupe on S.GRP equals G.CODE
join F in context.FILERE on G.FL equals F.CODE
select new { A.ID, A.ABSDate, A.STG, S.Nom, S.Prenom, S.GRP, G.FL })
.Where(X => X.STG.Contains(SearchBox.Text) ||
X.Nom.Contains(SearchBox.Text) ||
X.Prenom.Contains(SearchBox.Text) ||
X.GRP.Contains(SearchBox.Text))
.Select(x => new { x.ID, Date = x.ABSDate, x.Nom, Prénom = x.Prenom, Filiére = x.FL, Groupe = x.GRP })
.ToList();
However, when I use ABSDate
as part of the query, I get the following error:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.'
Broken Query
dataGridView1.DataSource = (from A in context.Absence
join S in context.Stagiaire on A.STG equals S.ID
join G in context.Groupe on S.GRP equals G.CODE
join F in context.FILERE on G.FL equals F.CODE
select new { A.ID, A.ABSDate, A.STG, S.Nom, S.Prenom, S.GRP, G.FL })
.Where(X => X.STG.Contains(SearchBox.Text) ||
X.Nom.Contains(SearchBox.Text) ||
X.Prenom.Contains(SearchBox.Text) ||
X.GRP.Contains(SearchBox.Text) ||
X.ABSDate.ToString("dd/MM/yyyy hh:mm").Contains(SearchBox.Text))
.Select(x => new { x.ID, Date = x.ABSDate, x.Nom, Prénom = x.Prenom, Filiére = x.FL, Groupe = x.GRP })
.ToList();
Clearly, I know that this is where the issue lies:
X.ABSDate.ToString("dd/MM/yyyy hh:mm").Contains(SearchBox.Text)
How can I format the SearchBox
value to dd/MM/yyyy hh:mm
, and search by it using Contains
method?