I have these two models with one-many relation:
[Table("User")]
public class User
{
public User()
{
Times = new HashSet<Time>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Guid { get; set; }
public virtual ICollection<Time> Times { get; set; }
}
[Table("Time")]
public class Time
{
[Key]
public long TimeId { get; set; }
public DateTime WorkDay { get; set; }
public Guid UserGuid { get; set; }
public virtual User User { get; set; }
}
And method in context class which returns DataTable. First implementation fails after query goes through .ToDataTable() extension (or .ToList() or whatever) with exception:
LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression
Second one goes perfectly fine. Question is why?
First implementation. It doesn't work
public DataTable GetDtProjectsForUser(User user)
{
var query = from time in Time
select new
{
WorkDay = time.WorkDay.ToShortDateString(),
};
return query.ToDataTable();
}
Second one. It DOES work
public DataTable GetDtProjectsForUser(User user)
{
var localUser = User.Find(user.Guid);
var query = from time in localUser.Times
select new
{
WorkDay = time.WorkDay.ToShortDateString(),
};
return query.ToDataTable();
}