0

the problem in this function when add this two lines.

UserImage = GetImagePath(db.Users.FirstOrDefault(x => x.Id == p.User_ID).Image),  
InsertDate = p.InsertDate.ToString("dd/MM/yyyy")

I need to custom Image Path and custom date format,show this problem.
LINQ to Entities does not recognize the method System.String ToString(System.String) method, and this method cannot be translated into a store expression

private static string GetImagePath(string ImageName)
{
    return System.Configuration.ConfigurationManager.AppSettings["websiteurl"].ToString() + "/uploads/" + ImageName;
}

[HttpGet]
[Route("Comments")]
public IHttpActionResult Comments(string Post_ID)
{
    var list = db
        .ShalehComments
        .Where(p => p.Shaleh_ID == Post_ID && p.ParentID == 0)
        .Select(p => new {
            ID = p.ID,
            Comment = p.Comment,
            User = db.Users.FirstOrDefault(x=> x.Id == p.User_ID).FullName,
            UserImage = GetImagePath(db.Users.FirstOrDefault(x => x.Id == p.User_ID).Image),//here problem
            InsertDate = p.InsertDate.ToString("dd/MM/yyyy")//and here
    }).ToList();

    return Ok(
        new
        {
            result = true,
            data = list
        }
    );
}

1 Answer 1

1

This error occurred because Entity Framework does not know how to execute .ToString() or GetImagePath method in sql. So you should load the data by using ToList.So you try something like:

[HttpGet]
[Route("Comments")]
public IHttpActionResult Comments(string Post_ID)
{
    var list = db
        .ShalehComments
        .Where(p => p.Shaleh_ID == Post_ID && p.ParentID == 0)
        .ToList()//add ToList
        .Select(p => new {
            ID = p.ID,
            Comment = p.Comment,
            User = db.Users.FirstOrDefault(x=> x.Id == p.User_ID).FullName,
            UserImage = GetImagePath(db.Users.FirstOrDefault(x => x.Id == p.User_ID).Image),
            InsertDate = p.InsertDate.ToString("dd/MM/yyyy")//and here
    }).ToList();

    return Ok(
        new
        {
            result = true,
            data = list
        }
    );
}
Sign up to request clarification or add additional context in comments.

4 Comments

But this method is expensive in performance. Are there other better ways?
another way you can do all conversion into SQL Query. but in EF when you execute sql query it return IEnumerable but it's expensive too. so i thing it better.
@WebDeveloper a stored procedure?
@PhilCooper If you use EF then same result as Raw Query .you get the result as IEnumerable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.