如何仅检索用户定义的SQL Server数据库模型属性

问题描述

我有类似的数据库模型

class A
{ 
    public string a;
    public string b;
    public string c;
    . 
    .
    .
}

我只想从数据库模型A中检索查询时的属性a和b,而不是检索整个模型A。在实体框架核心中使用存储过程可以做到这一点吗?

解决方法

 var result = dbcontext.Entity
   .Select(x => new { x.ServerName,x.ProcessID,x.Username })
   .ToList();

我想这会解决您的问题!

,

@Lincoln Teixeira的回答在技术上是正确的,但将返回匿名实例的列表。

在实际应用中,我们应该在业务逻辑内部使用DTO。在提供例如JSON,使用匿名类可能更合适。

public class MyDto
{
    public string A { get; set; }
    public string B { get; set; }

    public MyDto(string a,string b)
    {
        A = a;
        B = b;
    }
}

var result = dbcontext.Entity
  .Select(entity => new MyDto(entity.a,entity.b))
  .ToList();