[英]How to exclude one "column" in .ToListAsync() using EF Core?
我有一个async
函数的return
码:
return await _context.Models.ToListAsync();
这是成功返回这个:
[
{
"id":"id",
"name":"name",
"url":"url",
"components":[]
}
]
现在,我不想显示这样的components
。
[
{
"id":"id",
"name":"name",
"url":"url"
}
]
到目前为止,我尝试过:
return await _context.Models.Select( p => new Model {
Id = p.Id, Name = p.Name, Url = p.Url
}).ToListAsync();
但它仍然会显示components
并且只会使它的值无效。
那是因为如果您不提供编译器为其提供的默认值,您将创建一个新模型和事件。所以您需要创建一个新类并从中删除属性,或者您需要动态填充它并更改您的代码如下:
return await _context.Models.Select( p => new {
Id = p.Id, Name = p.Name, Url = p.Url
}).ToListAsync();
您应该创建新的模型类(DTO):
public class Model2
{
public int Id {get;set};
public string Name {get;set};
public string Url {get;set};
}
然后使用
p => new Model2 {
Id = p.Id, Name = p.Name, Url = p.Url
}).toListAsync
您可以使用这样的匿名类型:
return await _context.Models
.Select(p => new {
p.Id,
p.Name
});
或者使用除 components 属性之外的所有属性创建一个 DTO。
public class DTO
{
public string Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
然后:
.Select(p => new DTO {
Id = p.Id,
Name = p.Name,
Url = p.Url
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.