从实体框架中排除某些列选择参数

时间:2017-08-24 10:16:36

标签: c# entity-framework

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

我知道最好为图像制作一个单独的表格,但我没有这样做, 当我试图仅在没有图像的情况下列出产品时,有没有办法排除图像列?

2 个答案:

答案 0 :(得分:4)

product.Entity<Product>().Ignore(e => e.image);

{{1}}

答案 1 :(得分:2)

使用除图像属性之外的所有属性创建DTO:

public class YourDTO
{
    public string YourProperty1 { get; set; }
    public string YourProperty2 { get; set; }
    // etc
}

然后你可以这样做:

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

更新:

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

var product = context.Products
                     .Where(x => x.Id == productId)
                     .Select(x => new {
                         x.dbProperty1,
                         x.dbProperty2        
                         // etc, don't include the image column
                     });

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

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