c# - 将 linq 模型转换为通用列表

标签 c# linq linq-to-sql generics

我有一个现有的类 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/

相关文章:

c# - 用于检查日月年日期的 C# 函数

c# - 如何使用 Mono.Cecil 注入(inject)对 System.Object.Equals 的调用?

c# - Hangfire 配置问题(Common.Logging.Core & Common.Logging.LogManager)

c# - 使用 Linq 选择特定元素

linq-to-sql - linq to sql 是否有 with ties 选项?

c# - 检查 Int32.TryParse 的更简单方法

c# - 带美国日期的 OrderBy Linq

c# - 检查整数列表是否递增 1

c# - 什么使 LINQ 关联成为 EntitySet<table>?

c# - 为什么 LINQ 查询返回的结果/行数多于我正在查询的表?