C# Edit objects in linq expression in asp.net-mvc
Lets say I have the following code:
return (from p in repository.GetPostMedia() select p).ToList();
But in the values of object p, I want to inject a property calculated as follows:
MediaUrl = App.Resource["MediaPath"] + p.Id + "." + p.Ext;
PS. This code is located in the Service section of an ASP.NET MVC application. It is supposed to generate a url property and attach it to the returned object. If the controller is the best place to put this logic, how would I accomplish this with my code as follows:
public ActionResult PostMediaList(int postId)
{
var media = postService.GetMedia(); //the call to the code above.
return Json(media);
}
Media is generated from the LINQ to SQL in the repository. Also, i want to be able to change the path of where the media files are stored at a later da开发者_运维知识库te and just change something web project or service project only.
From what I understand of your question, you could return an anonymous type instead of whatever p is.
return (from p in repository.GetPostMedia()
select new { Media = p,
MediaUrl = App.Resource["MediaPath"] + p.Id + "." + p.Ext } ).ToList();
Create a wrapper class with the property you want, and return a collection of that class with your query.
Very, very basic and skeletal example:
class MyMedia
{
public MyMedia(Media m)
{
this.Media = m;
this.MediaUrl = App.Resource["MediaPath"] + m.Id + "." + m.Ext;
}
public Media Media
{
get; set;
}
public string MediaUrl
{
get; set;
}
}
and then, in your method:
return (from p in repository.GetPostMedia() select new MyMedia(p)).ToList();
精彩评论