我正在将实体框架和WebAPI与我的AngularJS项目一起使用。到目前为止,数据库中的整个表都转换为 JSON,但我真的只需要 3 列。有什么简单的方法可以解决这个问题吗?
更新:这是使用实体框架自动生成的控制器。该表包含具有项目信息的列,例如"项目ID","项目名称","客户名称"等。我只想要其中的几个,让我们说"项目ID"和"项目名称"。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using RetGet;
namespace RetGet.controllers
{
public class ProjectsController : ApiController
{
private censoredname db = new censoredname();
// GET: api/Projects
public IQueryable<Project> GetProject()
{
return db.Project;
}
// GET: api/Projects/5
[ResponseType(typeof(Project))]
public IHttpActionResult GetProject(int id)
{
Project project = db.Project.Find(id);
if (project == null)
{
return NotFound();
}
return Ok(project);
}
// PUT: api/Projects/5
[ResponseType(typeof(void))]
public IHttpActionResult PutProject(int id, Project project)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != project.ProjectId)
{
return BadRequest();
}
db.Entry(project).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Projects
[ResponseType(typeof(Project))]
public IHttpActionResult PostProject(Project project)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Project.Add(project);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = project.ProjectId }, project);
}
// DELETE: api/Projects/5
[ResponseType(typeof(Project))]
public IHttpActionResult DeleteProject(int id)
{
Project project = db.Project.Find(id);
if (project == null)
{
return NotFound();
}
db.Project.Remove(project);
db.SaveChanges();
return Ok(project);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProjectExists(int id)
{
return db.Project.Count(e => e.ProjectId == id) > 0;
}
}
}
经过大量的谷歌搜索,似乎在使用EF 6时,你必须使用 JSON.NET[数据合同]和[数据成员]。请参阅示例。
[DataContract]
public partial class Project
{
[DataMember]
public int ProjectId { get; set; }
public string PROJECT_NUMBER { get; set; }
public string PROJECT_NAME { get; set; }
[DataMember]
public string LONG_NAME { get; set; }
public decimal CUSTOMER_ID { get; set; }
public string CUSTOMER_NAME { get; set; }
}