从实体框架选择语句中排除某些列

Lai*_*ila 9 c# entity-framework

我在SQL Server数据库的产品表中有一个图像列。image列用于将图像另存为字节。

我知道最好为图像创建一个单独的表格,但是我没有这样做,所以当我尝试仅列出不含图像的产品时,有什么方法可以排除图像列吗?

tra*_*r0x 15

使用除 image 属性之外的所有属性创建一个 DTO:

public class YourDTO
{
    public string YourProperty1 { get; set; }
    public string YourProperty2 { get; set; }
    // etc
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

var productDto = context.Products
                        .Where(x => x.Id == productId)
                        .Select(x => new YourDTO {
                            YourProperty1 = x.DbProperty1,
                            YourProperty2 = x.DbProperty2        
                            // etc, don't include the image column
                        });
Run Code Online (Sandbox Code Playgroud)

更新:

如果您不想将结果映射到YourDTO,则可以投影到匿名类型:

var product = context.Products
                     .Where(x => x.Id == productId)
                     .Select(x => new {
                         x.DbProperty1,
                         x.DbProperty2        
                         // etc, don't include the image column
                     });
Run Code Online (Sandbox Code Playgroud)

...如果您想为匿名类型的每个属性提供自定义名称:

var product = context.Products
                     .Where(x => x.Id == productId)
                     .Select(x => new {
                         YourProperty1 = x.DbProperty1,
                         YourProperty2 = x.DbProperty2        
                         // etc, don't include the image column
                     });
Run Code Online (Sandbox Code Playgroud)

上述所有方法在功能上等同于以下 SQL:

SELECT p.DbProperty1, p.DbProperty2 
FROM products p
WHERE p.Id = WhateverId;
Run Code Online (Sandbox Code Playgroud)


小智 5

product.Entity<Product>().Exclude(e => e.image); 
Run Code Online (Sandbox Code Playgroud)

要么

product.Entity<Product>().Ignore(e => e.image);
Run Code Online (Sandbox Code Playgroud)

  • 您根本没有提供任何上下文,这就是为什么我给您-1的原因。我猜您的建议是基于DbContext类的OnModelCreating方法?因此,这不是忽略select的方法,而是忽略完整的`DbContext`。 (4认同)
  • @Laila您已经调用了`ToList()`,它将执行整个查询并将其转储到`List &lt;&gt;`对象中。 (2认同)