LINQ选择语法将返回所有列而不是选定的列
问题描述:
我试图从表中选择并返回某些列,查询将忽略该选择并返回除相关表中相关字段以外的所有列。 如何仅返回选定的列?LINQ选择语法将返回所有列而不是选定的列
这是我API Controller
,
[Produces("application/json")]
[Route("api/Common")]
public class CommonController : Controller
{
private readonly ArtCoreDbContext _context;
public CommonController(ArtCoreDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<IdState> GetState()
{
return _context.IdState;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetState([FromRoute] int id)
{
var L2EQuery = await (from i in _context.IdState
select new { Id = i.StaeId, i.text }).ToListAsync();
return Ok(L2EQuery);
}
}
更新
这是模型,
public class IdState
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
public int StaeId { set; get; }
public int CouyId { set; get; }
[Display(Name = "State"), Required]
public string text { set; get; }
public ICollection<PatReg> State { get; set; }
public ICollection<IdCity> TblIdCity { get; set; }
}
和输出,
[{
"staeId": 1,
"couyId": 2,
"text": "California",
"state": null,
"tblIdCity": null
}, {
"staeId": 2,
"couyId": 2,
"text": "WA",
"state": null,
"tblIdCity": null
}, {
"staeId": 3,
"couyId": 1,
"text": "Ajloun",
"state": null,
"tblIdCity": null
}, {
"staeId": 4,
"couyId": 1,
"text": "Amman",
"state": null,
"tblIdCity": null
}]
ajax
呼叫
使用LINQPad 5我得到的只有选中的列,
答
我认为,你可以调用方法public IEnumerable<IdState> GetState()
并返回给你整个表。
也许,你需要调用Task<IActionResult> GetState([FromRoute] int id)
问题是在这里: url: "/api/Common",
你叫错了方法,添加参数:
url: "/api/Common/123",
或可能:
$(function() {
$.ajax({
type: "Get",
url: "/api/Common",
data: {id: 123},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
答
可以吗请试试
public class CommonController : Controller
{
private readonly ArtCoreDbContext _context;
public CommonController(ArtCoreDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<IdState> GetState()
{
return _context.IdState;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetState([FromRoute] int id)
{
var L2EQuery = await (from i in _context.IdState
where i.test.equals("abc")
select new { Id = i.StaeId, text= i.text }).ToListAsync();
return Ok(L2EQuery);
}
}
答
您的C#代码没有问题,但JavaScript。
您没有在控制器中指定操作,因此它默认为无参数HttpGet
启用操作,该操作不会投影任何字段。所以问题在于你的AJAX调用。更正像这样:
$.ajax({
type: "Get",
// Pay attention on the next line !
url: "/api/Common/123",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
“123”只是一个例子,但是我所看到的,目前也没有关系,因为你不过滤你的LINQ什么。但是,您必须在URL中指定它,以便可以将其解析为正确的方法。
您如何看到它比ID和文本更多地返回? – Backs
我米用'ajax'并输出到'console' – JSON
显示'IdState'类和输出 – Backs