【发布时间】:2017-03-16 18:10:54
【问题描述】:
我有一个获取所有品牌的控制器,之前我使用的是 DTO,但发现了匿名对象,所以我决定试一试。
我使用 DTO 的 get 方法如下:
public async Task < IHttpActionResult > GetBrand(int id) {
var brand = await db.Brand.Select(x => new {
brandDesc = x.brandDesc,
BrandId = x.BrandId,
brandLogoUrl = x.brandLogoUrl,
brandName = x.brandName,
Products = x.Products.Select(y => new {
productDesc = y.productDesc,
ProductId = y.ProductId,
productName = y.productName,
productPrice = y.productPrice,
productStock = y.productStock,
productStatus = y.productStatus,
productModifyDate = y.productModifyDate
}).ToList()
}).FirstOrDefaultAsync(x => x.BrandId == id);
if (brand == null) {
return NotFound();
}
return Ok(brand);
}
我的带有匿名对象的新代码如下所示:
public async Task < IHttpActionResult > GetBrand(int id) {
var brand = await db.Brand.Select(x => new {
x.brandDesc,
x.BrandId,
x.brandLogoUrl,
x.brandName,
x.Products
}).FirstOrDefaultAsync(x => x.BrandId == id);
if (brand == null) {
return NotFound();
}
return Ok(brand);
}
它们都返回相同的输出:
[{
"brandDesc": "Dicalc phos crys-forearm",
"BrandId": 7,
"brandLogoUrl": "http://dummyimage.com/159x219.png/5fa2dd/ffffff",
"brandName": "ALK-Abello, Inc.",
"Products": [
{
"productDesc": "Unspecified umbilical cord complication complicating labor and delivery, antepartum condition or complication",
"ProductId": 70,
"productName": "Bigtax",
"productPrice": 4445.17,
"productStock": 39,
"productStatus": true,
"productModifyDate": "2016-06-03T08:26:24"
},
{
"productDesc": "Adhesions of iris, unspecified",
"ProductId": 598,
"productName": "It",
"productPrice": 1240.36,
"productStock": 35,
"productStatus": false,
"productModifyDate": "2016-06-04T01:00:54"
}
]
}]
这里真的我的问题是C#编译器如何知道如何映射内部对象并且不重复属性,例如在Brands类中我有一个brandID和一个Product对象,Product类也有一个brandId,当我使用 DTO 我必须在 Brand DTO 中指定手动映射brandId 并在 ProductDTO 中删除该属性,因此数据不会重复,但是当我在内部使用匿名对象 c# 时,内部对象(产品)也是由自动完成的C#。我真的很惊讶 c# 可以在不需要手动指定的情况下做到这一点
编辑:还发现我可以在匿名对象中手动指定一个属性:
Products = x.Products.Select(y => new {
productDesc = y.productDesc,
ProductId = y.ProductId,
productName = y.productName,
productPrice = y.productPrice,
y.productStock,
y.productStatus,
y.productModifyDate}).ToList()
并且只指定我想要的属性
【问题讨论】:
-
仅供参考,当您像这样格式化代码时,它很难阅读
-
我认为您的
Products类没有BrandId属性。这里没有魔法。编译器不参与塑造结果。您看到的只是 Json 序列化程序 Json.Net 的结果。这也不会像那样删除属性。我确定BrandId不是从那里开始的,或它不是公共属性,或它有一个 JsonIgnore 属性。
标签: c# entity-framework object anonymous