我通过参考https://github.com/OData/ODataSamples/tree/master/WebApiCore/DynamicEdmModelCreation完成了动态edm模型的创建。
我已将odata查询选项添加到上述项目中。 $ filter,$ top,$ count,$ select(不展开)已成功运行。但是当我查询~/odata/Products?$expand=DetailInfo
时-它没有为DetailInfo返回任何值。有人可以帮我解决以上问题吗
EdmEntityObject entity = new EdmEntityObject(entityType);
entity.TrySetPropertyValue("Name", "abc");
entity.TrySetPropertyValue("ID", 1);
entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(88,"abc_detailinfo", entity.ActualEdmType));
collection.Add(entity);
entity = new EdmEntityObject(entityType);
entity.TrySetPropertyValue("Name", "def");
entity.TrySetPropertyValue("ID", 2);
entity.TrySetPropertyValue("DetailInfo", CreateDetailInfo(99, "def_detailinfo", entity.ActualEdmType));
collection.Add(entity);
执行上述代码后,集合将保存2个值,每个值具有3个属性,2个结构属性(名称,id)和1个导航属性,其中包含DetailInfo的值。
当前输出:
[{"Name":"abc","ID":1},{"Name":"def","ID":2}]}
预期输出:
[{"Name":"abc","ID":1, "DetailInfo":{"ID":88,"Title":"abc_detailinfo"}},{"Name":"def","ID":2, "DetailInfo":{"ID":99,"Title":"def_detailinfo"}}]}
答案 0 :(得分:0)
使用动态EDM模型创建时,您必须实现自己应用ODataQueryOptions的逻辑。
这意味着您控制器中的GET(id)方法如下所示。
public IEdmEntityObject Get(string key)
{
// Get entity type from path.
ODataPath path = Request.ODataFeature().Path;
IEdmEntityType entityType = (IEdmEntityType)path.EdmType;
// Create an untyped entity object with the entity type.
EdmEntityObject entity = new EdmEntityObject(entityType);
string sourceString = Request.GetDataSource();
DataSourceProvider.Get(sourceString, key, entity);
IEdmModel model = Request.GetModel();
ODataQueryContext queryContext = new ODataQueryContext(model, entityType, path);
ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, Request);
// Apply query options here.
return entity;
}
这意味着您控制器中的GET方法如下所示。
public EdmEntityObjectCollection Get()
{
// Get entity set's EDM type: A collection type.
ODataPath path = Request.ODataFeature().Path;
IEdmCollectionType collectionType = (IEdmCollectionType)path.EdmType;
IEdmEntityTypeReference entityType = collectionType.ElementType.AsEntity();
// Create an untyped collection with the EDM collection type.
EdmEntityObjectCollection collection =
new EdmEntityObjectCollection(new EdmCollectionTypeReference(collectionType));
string sourceString = Request.GetDataSource();
// Add untyped objects to collection.
DataSourceProvider.Get(sourceString, entityType, collection);
IEdmModel model = Request.GetModel();
ODataQueryContext queryContext = new ODataQueryContext(model, collectionType.AsElementType(), path);
ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, Request);
// Apply query options here.
return collection;
}