이전에 DTO를 사용했지만 익명 객체를 발견하여 모든 시도를 허용하기로 결정한 모든 컨트롤러를 가져 오는 컨트롤러가 있습니다. 익명 객체 작동 방법 C# 엔티티 프레임 워크
는 DTO의를 사용하여 내 get 메소드이었다 다음[{
"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"
}
]
:
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);
}
그들은 모두 같은 출력을 반환 : 익명 개체
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);
}
나의 새로운 코드는 다음과 같습니다
}]
정말로 내 질문은 C# 컴파일러가 내부 객체를 매핑하는 방법을 알고 속성을 반복하지 않는다는 것입니다 (예 : 브랜드 클래스에서 brandID 및 Product 객체가있는 경우, DTO를 사용할 때 Product 클래스에도 brandId가있는 경우). 나는 수동으로 브랜드 DTO에 brandId를 지정하고 ProductDTO에서 해당 속성을 삭제하여 데이터가 반복되지 않도록해야하지만 익명 객체를 사용할 때 내부적으로 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()
그리고 속성 만 지정 : 또한 내가 수동으로 익명 객체에서 속성을 지정할 수 있다는 것을 발견 : 나는 C#을 수동에게
편집을 지정할 필요없이이 작업을 수행 할 수 있다는 것을 정말 놀랐어요 내가 원하는 것
참고하시기 바랍니다. 코드를 형식화하면 읽을 때 매우 어려워집니다. – maccettura
'Products' 클래스에 'BrandId' 속성이 있다고 생각하지 않습니다. 여기에는 어떤 마법도 없습니다. 컴파일러는 결과를 형성하는 데 관여하지 않습니다. Json 시리얼 라이저 인 Json.Net의 결과 만 볼 수 있습니다. 그것도 그렇게 속성을 제거하지 않습니다. 나는'BrandId'가 시작하지 않아도된다는 것을 확신합니다 * 또는 * public 속성이 아니거나 * JsonIgnore 속성을가집니다. –