Convert linq model to general list

I have an existing Image class that is widely used throughout the application. I need to return the general image list (List) to the external interface, but since there is no stored procedure on the 3-bit side of the database, I require that I have to use Linq for Sql.

I created a dbtm database file that I request in my DAL, which looks like this:

ImageCat
    ImageId
    Name
    Width
    DateModified
    Height
    CatId

The 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 don't want to iterate over the linq result in Sql to tune my list. Is there an easier way. What is the best practice? I don't like the idea of ​​exposing my dbml classes to presentation level.

+3
3

Image LINQ

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();
+5

:

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(); 
0
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 these lines will give you an IEnumerable filled with Image objects. I wrote this in the edit window, so that I could be far away. Try it and let me know if this works for you.

-1
source

Source: https://habr.com/ru/post/1769122/


All Articles