views:

45

answers:

3

hi,

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.

+4  A: 

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();
Albin Sunnanbo
Thanks, works great
skyfoot
A: 

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(); 
klausbyskov
Works OK, but you will be creating a bunch of temporary ImageCat objects along the way.
Albin Sunnanbo
@Albin, you are correct. I have fixed the code.
klausbyskov
A: 
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.

Adkins
There are roughly three errors preventing this code from compiling.
Albin Sunnanbo
looking that over now, as well as looking at the selected answer I am seeing them. I think some more might come up after fixing those too. Sorry for the crappy code (as it was written in the editor), but the idea was sound :P
Adkins