Adding a custom query backed Navigation Property to ODataConventionModelBuilder

asp.net-web-api asp.net-web-api2 c# entity-framework odata

Accepted Answer

The EntitySet has to have "AddNavigationTarget" called on it. In your WebApiConfig.cs file, add the following code, assuming your namespace is "MyNamespace." This will enable "Get: odata/Cars(1)/Parts" to successfully retrieve the data.

    var cars = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("Cars");
    var parts = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("Parts");
    var carType = (EdmEntityType)edmModel.FindDeclaredType("MyNamespace.Car");
    var partType = (EdmEntityType)edmModel.FindDeclaredType("MyNamespace.Part");

    var partsProperty = new EdmNavigationPropertyInfo();
    partsProperty.TargetMultiplicity = EdmMultiplicity.Many;
    partsProperty.Target = partType;
    partsProperty.ContainsTarget = false;
    partsProperty.OnDelete = EdmOnDeleteAction.None;
    partsProperty.Name = "Parts";

    cars.AddNavigationTarget(carType.AddUnidirectionalNavigation(partsProperty), parts);
7
4/16/2014 3:12:16 PM

Popular Answer

Continuing with @FengZhao's response, you also need to register the navigation property link builder to entity set link builder in order to have the url odata/Cars working.

var cars = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("Cars");
var parts = (EdmEntitySet)edmModel.EntityContainers().Single().FindEntitySet("Parts");
var carType = (EdmEntityType)edmModel.FindDeclaredType("MyNamespace.Car");
var partType = (EdmEntityType)edmModel.FindDeclaredType("MyNamespace.Part");

var partsProperty = new EdmNavigationPropertyInfo();
partsProperty.TargetMultiplicity = EdmMultiplicity.Many;
partsProperty.Target = partType;
partsProperty.ContainsTarget = false;
partsProperty.OnDelete = EdmOnDeleteAction.None;
partsProperty.Name = "Parts";

var navigationProperty = carType.AddUnidirectionalNavigation(partsProperty);
cars.AddNavigationTarget(navigationProperty, parts);

var linkBuilder = edmModel.GetEntitySetLinkBuilder(cars);
linkBuilder.AddNavigationPropertyLinkBuilder(navigationProperty, 
    new NavigationLinkBuilder((context, property) =>
        context.GenerateNavigationPropertyLink(property, false), true));


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow