Web Developer
Web Developer

Reputation: 25

How to custom response in asp.net web api2

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
        }
    );
}

Upvotes: 0

Views: 65

Answers (1)

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

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
        }
    );
}

Upvotes: 1

Related Questions