将Linq模型转换为通用列表

3

我有一个现有的Image类,在我的应用程序中广泛使用。

我需要将图像的通用列表(List)返回给前端,但由于在我查询的第三方数据库中没有存储过程,因此我需要使用Linq to Sql。

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

ImageCat
    ImageId
    Name
    Width
    DateModified
    Height
    CatId

我的Image类如下:

public class Image
{
 public int Id { get; set; }
 public string Name { get; set; }
 public int Width { get; set; }
 public int Height { get; set; }
}

我的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);   
}

我不想遍历Linq to Sql结果来设置我的列表。有更简单的方法吗?最佳实践是什么?我不喜欢将我的dbml类暴露给表示层。

3个回答

5

您可以直接在 LINQ 查询中选择您的 Image 类。

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

0
你可以这样做:
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(); 

工作正常,但是你会在途中创建一堆临时的ImageCat对象。 - Albin Sunnanbo

-1
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();

我觉得大致上这样做会给你一个填充有Image对象的IEnumerable。不过,我是在编辑窗口中写的,所以可能完全错误。试一下,看看效果如何,然后告诉我。


1
大致上有三个错误阻止了这段代码的编译。 - Albin Sunnanbo
我现在正在查看它,以及查看所选答案。我认为在修复这些之后可能会出现更多问题。很抱歉代码很糟糕(因为是在编辑器中编写的),但是想法是正确的:P - Christopher B. Adkins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接