I have a list of students in a SQL CE 4.0 database. Each one has an insert time associated with the student. Here is the context setup.
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public DateTime InsertTime { get; set; }
}
public class StudentContext : DbContext
{
public StudentContext()
: base("StudentContext")
{ }
public DbSet<Student> Students { get; set; }
}
Inserting a new student works great as shown below:
static void AddStudent(string name)
{
using (var db = new StudentContext())
{
var s = new Student()
{
Name = name,
InsertTime = DateTime.Now
};
db.Students.Add(s);
db.SaveChanges();
}
}
The issue I am running into is that when I want to DELETE entries from the database after a given amount of time, using the linq to entities to query for entries that are older than a period of time fails. Below is my first attempt to look for entries older than 30 seconds.
var student = (from x in db.Students
where x.Name == name
&& x.InsertTime.AddSeconds(30) < DateTime.Now
select x).ToList();
This fails with the following error:
LINQ to Entities does not recognize the method 'System.DateTime
AddSeconds
Ok so apparently I need something linq will understand. Looking though StackOverflow I was able to find a method called EntityFunctions and modified my code as follows:
System.Data.Objects.EntityFunctions.AddSeconds(x.InsertTime, 30) < DateTime.Now
This also fails with the following error:
The function is not recognized by SQL Server Compact. [ Name of
function = ADDSECONDS...
Great, after more digging I found that the EntityFunctions only work with the SQL Provider, and not the SQL CE 4.0 provider. Perfect!
The only thing I could come up with was getting the list of entries and then filtering that collection once again.
var student = (from x in db.Students
where x.Name == name
select x).ToList();
var filteredStudent = student.Where(s => s.InsertTime.AddSeconds(30) < DateTime.Now).ToList();
This does work and the correct data is now available for deletion. However, the query could potentially return a large set of data, only to be filtered down to a couple of entries. The ADDDATE() is supported by Sql Compact CE 4.0. Is there any way I could write my own extension to the Linq to entities that would allow me to utilize the function? Can you think of another way to solve this problem?