将linq模型转换为通用列表

sky*_*oot 3 c# linq generics linq-to-sql

我有一个现有的类Image,在我的应用程序中广泛使用.我需要将一个通用的图像列表(List)返回到前端,但由于3ed方DB中没有存储过程,我正在查询我需要使用Linq to Sql.

我已经在我的DAL中创建了一个我正在查询的数据库的dbtm文件,如下所示:

ImageCat
    ImageId
    Name
    Width
    DateModified
    Height
    CatId
Run Code Online (Sandbox Code Playgroud)

我的Image类如下

public class Image
{
 public int Id { get; set; }
 public string Name { get; set; }
 public int Width { get; set; }
 public int Height { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的Linq to Sql如下:

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);   
}
Run Code Online (Sandbox Code Playgroud)

我不想通过linq循环到Sql结果来设置我的列表.有没有更简单的方法.什么是最佳做法?我不喜欢将我的dbml类暴露给表示层的想法.

Alb*_*nbo 5

您可以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();
Run Code Online (Sandbox Code Playgroud)