简体   繁体   English

如何在webAPI方法中获取表的特定列

[英]How to get Specific column of a table in webAPI method

I have a MVC4 application with a WebApi method which is getting entire table data from database. 我有一个带有WebApi方法的MVC4应用程序,该方法正在从数据库中获取整个表数据。 Now i want to extract only two columns from it. 现在我只想从中提取两列。 How can I do it? 我该怎么做?

I know that arrays will be used to do so but don't know the syntax in .net. 我知道将使用数组来执行此操作,但是不知道.net中的语法。 This is my WebAPi function which is getting the entire table data from the SQL server database: 这是我的WebAPi函数,该函数从SQL Server数据库获取整个表数据:

namespace BRDCEP_MIS.Areas.BRDCEP.Controllers
{
    public class WebApiController : ApiController
    {

        //api get method.

        //[Route("WebApi/GetPscTargets")]

        public HttpResponseMessage Get() {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {

                List<PscDistrictTargets> xx = new List<PscDistrictTargets>();
                xx = db.PscDistrictTargetss.ToList();
                //xx.ID = Convert.ToString(DATA);
                HttpResponseMessage response = new HttpResponseMessage();
                response = Request.CreateResponse(HttpStatusCode.OK, xx);
                return response;
            }

        }

    }
}

You can use the Select method and do a projection on only those properties you needed to an an object of your DTO/view model to represent this data, in your LINQ query. 您可以使用Select方法,并仅在LINQ查询中对DTO /视图模型的对象来表示此数据所需的那些属性进行投影。

So create a DTO class to represent the data you want with only those properties, 因此,请创建一个DTO类,以便仅使用这些属性来表示所需的数据,

public class MyDto
{
    public int TargetId { set; get; }
    public string TargetName { set; get; }
}

Now update your LINQ query use the Select method to get only those properties and project those our dto object. 现在,使用Select方法更新您的LINQ查询,以仅获取那些属性并投影那些我们的dto对象。

var items = db.PscDistrictTargetss
              .Select(f => new MyDto { TargetName = f.Name, 
                                       TargetId = f.Id})
              .ToList();
return Request.CreateResponse(HttpStatusCode.OK, items );

Assuming PscDistrictTargets entity class has a Name and Id property. 假设PscDistrictTargets实体类具有NameId属性。 Update that part based on your actual property names. 根据您的实际属性名称更新该部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM