Reputation: 20769
I have an existing class Image which is used extensively throughout my application. I need to return a generic list of images (List) to the frontend but as there is no stored proc in the 3ed party DB I am quering I need to use Linq to Sql.
I have create a dbtm file of the database I am quering in my DAL which looks like:
ImageCat
ImageId
Name
Width
DateModified
Height
CatId
My Image class is as follows
public class Image
{
public int Id { get; set; }
public string Name { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
My Linq to Sql is as follows:
var imageList = (from ic in db.ImageCats
where ic.CatID.Contains(category)
select ic).ToList();
var finalImageList = new List<Image>();
foreach (ImageCat ic in imageList)
{
Image image = new Image();
image.Id= ic.ImageID;
image.Height = (int)ic.Height;
image.Name = ic.Name;
image.Width = (int)ic.Width;
finalImageList.Add(image);
}
I dont want to be looping through the linq to Sql result to setup my List. Is there an easier way. What is best practice? I dont like the idea of exposing my dbml classes to the presentation layer.
Upvotes: 3
Views: 7011
Reputation: 3567
IEnumerable<Image> = from ic in db.ImageCats
where ic.CatID.Contains(category)
select new Image() { Id= ic.ImageID, Height = (int)ic.Height, Name = ic.Name, Width = (int)ic.Width }.ToList();
I think something along those lines will give you an IEnumerable filled with Image objects. I wrote that in the editing window so I could be way off though. Try it out and let me know if it worked out for you.
Upvotes: -1
Reputation: 120917
You can do it like so:
var imageList = db.ImageCats.Where(ic => ic.CatID.Contains(category))
.Select(ic => new Image{ Id = ic.ImageID,
Height = (int)ic.Height,
Name = ic.Name,
Width = (int)ic.Width})
.ToList();
Upvotes: 0
Reputation: 47038
You can select directly to you Image
class in the LINQ query
var imageList = (
from ic in db.ImageCats
where ic.CatID.Contains(category)
select new Image()
{
Id= ic.ImageID,
Height = (int)ic.Height,
Name = ic.Name,
Width = (int)ic.Width,
}
).ToList();
Upvotes: 5