0
votes

I'm trying to get custom set of data from entity query, but regratfully I'm getting the following error:

LINQ to Entities does not recognize the method System.String ToString() method, and this method cannot be translated into a store expression. Here is custome class to return data:

public class featuredlist
{
    public string kodg { get; set; }
    public string excursion { get; set; }
    public string excursiondate { get; set; }
}

public IQueryable<featuredlist> GetFeatured(string fdate)
{
   try
   {
     var fd = DateTime.Parse(fdate);
     var uname = HttpContext.Current.User.Identity.Name;
     var uid = (from x in db.xEmployee where x.Сотрудник.Contains(uname) 
                                             select x.Kod).FirstOrDefault();
     var fl = (from a in db.xGrafik
                         join b in db.xExcursion on a.Excursion equals b.Kod
                         join c in db.xDate on a.КодД equals c.Kod
                         join d in db.xOrder on a.Kod equals d.КодГ
                         where c.Дата == fd & d.Продал == uid
                         orderby c.Дата descending
                         select new featuredlist
                         {
                             kodg = a.Kod.ToString(),
                             excursion = b.Название,
                             //Probably error happend here.
                             excursiondate = 
                             (c.Дата) != null ? 
                                         c.Дата.Value.ToShortDateString :
                                         "01.01"
                         })
                           .AsQueryable();
                return fl.Distinct();
    }
    catch (DbEntityValidationException e)
    {
      foreach (var eve in e.EntityValidationErrors)
      {
        var path = @"d:\error.txt";
        using (StreamWriter sw = File.CreateText(path))
        {
           sw.WriteLine("Entity of type \"{0}\" in state \"{1}\" has 
                         the following validation errors:",
           eve.Entry.Entity.GetType().Name, eve.Entry.State);
        }
        using (StreamWriter sw1 = File.CreateText(@"d:\error1.txt"))
              foreach (var ve in eve.ValidationErrors)
              {
                sw1.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                              ve.PropertyName, ve.ErrorMessage);
              }
      }
      throw;
    }               
}

Exception message: "LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression." Stack trace: " в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.DefaultTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator1.Translate(ExpressionConverter parent, Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator1.Translate(ExpressionConverter parent, Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SelectTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator1.Translate(ExpressionConverter parent, Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator1.Translate(ExpressionConverter parent, Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) в System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert() в System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable1 forMergeOption) в System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__a() в System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) в System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__9() в System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) в System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) в System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0() в System.Lazy1.CreateValue() в System.Lazy1.LazyInitValue() в System.Lazy1.get_Value() в System.Data.Entity.Internal.LazyEnumerator1.MoveNext() в Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) в Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) в Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType) в Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType) в Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value) в System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) в System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) в System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) в System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- Конец трассировка стека из предыдущего расположения, где возникло исключение --- в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) в System.Runtime.CompilerServices.TaskAwaiter.GetResult() в System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"

2
Can you please add the exception description with the stack trace to the question description?Ivan Zub
Yes, question sound similar, but error source and solution are different.andrey.shedko

2 Answers

0
votes

Everything in your fl query must be translatable to valid SQL. ToString is not, you have to use SqlFunctions.StringConvert instead:

kodg = SqlFunctions.StringConvert(a.Kod),

Or you can retrieve your results first (AsEnumerable), then project (select) in an inproc query.

0
votes

The problem was about custom class that must return custom data. When I change its to be as follow (DateTime? instead of string) it's working fine:

public class featuredlist
        {
            public int kodg { get; set; }
            public string excursion { get; set; }
            public DateTime? excursiondate { get; set; }
        }