我有一个现有的类 Image,它在我的整个应用程序中被广泛使用。 我需要将通用图像列表 (List) 返回到前端,但由于 3ed 方数据库中没有存储过程,我正在查询我需要使用 Linq to Sql。
我已经在我的 DAL 中创建了一个我正在查询的数据库的 dbtm 文件,它看起来像:
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 类暴露给表示层的想法。
最佳答案
您可以在 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();
关于c# - 将 linq 模型转换为通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3914204/