データベースからデータを取得するdapper micro ormを使用して、C#バックエンドでanglejsアプリケーションを構築しています。この特定の方法でデータを返すにはどうすればいいですか?
私は、データがこのように見えるように返さたかった:
[{
"CategoryId": 1,
"CategoryName": "cat1",
"Items": [{
"ItemId": 1,
"ItemName": "Item1"
}, {
"ItemId": 2,
"ItemName": "Item2"
}]
}, {
"CategoryId": 2,
"CategoryName": "cat2",
"Items": [{
"ItemId": 3,
"ItemName": "Item3"
}, {
"ItemId": 4,
"ItemName": "Item4"
}]
}
]
が、これは私のデータが
[{
"CategoryId": 1,
"CategoryName": "cat1",
"Items": {
"ItemId": 1,
"ItemName": "Item1"
}
}, {
"CategoryId": 1,
"CategoryName": "cat1",
"Items": {
"ItemId": 2,
"ItemName": "Item2"
}
},
{
"CategoryId": 2,
"CategoryName": "cat2",
"Items": {
"ItemId": 3,
"ItemName": "Item3"
}
},
{
"CategoryId": 2,
"CategoryName": "cat2",
"Items": {
"ItemId": 4,
"ItemName": "Item4"
}
}
]
どのように見えるかこれは私が私のリポジトリ内に持っているものです。
public IEnumerable<CategoryModel> GetAllCategories()
{
using (var conn = ConnectionSettings.GetSqlConnection())
{
const string sql = @" SELECT
c.CategoryName,
c.CategoryId,
i.ItemId,
i.ItemName,
i.CategoryId
from Category c
INNER JOIN item i ON c.CategoryId = i.CategoryId";
var categoriesList = conn.Query<CategoryModel, ItemModel, CategoryModel>(sql, (cat, it) =>
{
cat.Item = it;
return cat;
}, splitOn: "ItemId");
return categoriesList;
}
}
これは私のカテゴリとアイテムのモデルです
public class CategoryModel
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ItemModel Item { get; set; }
}
public class ItemModel
{
public int ItemId { get; set; }
public int CategoryId { get; set; }
public string ItemName { get; set; }
}
誰かが正しい方向に向いていますか?
私がここで間違っていることを教えてください。以下に示すようにNewtonsoft JSONでシリアライズを避けるために、ItemModel
でCategoryId
を無視する属性を使用し、エンティティを変更
:事前
:結果は個別に設定し、コードは次のようになります両方フェッチする。現時点ではオブジェクトであり、したがって1つのように非直列化されています。 – M22an