"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Containment in OData v4 Using Web API 2.2

by Jinfu Tan

Traditionally, an entity could only be accessed if it were encapsulated inside an entity set. But OData v4 provides two additional options, Singleton and Containment, both of which WebAPI 2.2 supports.

This topic shows how to define a containment in an OData endpoint in WebApi 2.2. For more information about containment, see Containment is coming with OData v4. To create an OData V4 endpoint in Web API, see Create an OData v4 Endpoint Using ASP.NET Web API 2.2.

First, we’ll create a containment domain model in the OData service, using this data model:

Data model
Data model

An account contains many PaymentInstruments (PI), but we don’t define an entity set for a PI. Instead, the PIs can only be accessed through an Account.

You can download the solution used in this topic from CodePlex.

Defining the data model

  1. Define the CLR types.

    [!code-csharpMain]

       1:  public class Account     
       2:  {         
       3:      public int AccountID { get; set; }         
       4:      public string Name { get; set; }         
       5:      [Contained]         
       6:      public IList<PaymentInstrument> PayinPIs { get; set; }     
       7:  }     
       8:   
       9:  public class PaymentInstrument     
      10:  {         
      11:      public int PaymentInstrumentID { get; set; }        
      12:      public string FriendlyName { get; set; }     
      13:  }

    The Contained attribute is used for containment navigation properties.
  2. Generate the EDM model based on the CLR types.

    [!code-csharpMain]

       1:  public static IEdmModel GetModel()         
       2:  {             
       3:      ODataConventionModelBuilder builder = new ODataConventionModelBuilder();             
       4:      builder.EntitySet<Account>("Accounts");             
       5:      var paymentInstrumentType = builder.EntityType<PaymentInstrument>();             
       6:      var functionConfiguration = 
       7:          paymentInstrumentType.Collection.Function("GetCount");             
       8:      functionConfiguration.Parameter<string>("NameContains");             
       9:      functionConfiguration.Returns<int>();             
      10:      builder.Namespace = typeof(Account).Namespace;             
      11:      return builder.GetEdmModel();         
      12:  }

    The ODataConventionModelBuilder will handle building the EDM model if the Contained attribute is added to the corresponding navigation property. If the property is a collection type, a GetCount(string NameContains) function will also be created.

    The generated metadata will look like the following:

    [!code-xmlMain]

       1:  <EntityType Name="Account">   
       2:    <Key>     
       3:      <PropertyRef Name="AccountID" />   
       4:    </Key>   
       5:    <Property Name="AccountID" Type="Edm.Int32" Nullable="false" />   
       6:    <Property Name="Name" Type="Edm.String" />   
       7:    <NavigationProperty 
       8:      Name="PayinPIs" 
       9:      Type="Collection(ODataContrainmentSample.PaymentInstrument)" 
      10:      ContainsTarget="true" /> 
      11:  </EntityType>

    The ContainsTarget attribute indicates that the navigation property is a containment.

Define the containing entity set controller

Contained entities don’t have their own controller; the action is defined in the containing entity set controller. In this sample, there is an AccountsController, but no PaymentInstrumentsController.

[!code-csharpMain]

   1:  public class AccountsController : ODataController     
   2:  {         
   3:      private static IList<Account> _accounts = null;         
   4:      public AccountsController()         
   5:      {             
   6:          if (_accounts == null)             
   7:          {                 
   8:              _accounts = InitAccounts();             
   9:          }         
  10:      }         
  11:      // PUT ~/Accounts(100)/PayinPIs         
  12:      [EnableQuery] 
  13:      public IHttpActionResult GetPayinPIs(int key)         
  14:      {             
  15:          var payinPIs = _accounts.Single(a => a.AccountID == key).PayinPIs;             
  16:          return Ok(payinPIs);         
  17:      }         
  18:      [EnableQuery]         
  19:      [ODataRoute("Accounts({accountId})/PayinPIs({paymentInstrumentId})")]         
  20:      public IHttpActionResult GetSinglePayinPI(int accountId, int paymentInstrumentId)         
  21:      {             
  22:          var payinPIs = _accounts.Single(a => a.AccountID == accountId).PayinPIs;             
  23:          var payinPI = payinPIs.Single(pi => pi.PaymentInstrumentID == paymentInstrumentId);             
  24:          return Ok(payinPI);         
  25:      }         
  26:      // PUT ~/Accounts(100)/PayinPIs(101)         
  27:      [ODataRoute("Accounts({accountId})/PayinPIs({paymentInstrumentId})")]         
  28:      public IHttpActionResult PutToPayinPI(int accountId, int paymentInstrumentId, [FromBody]PaymentInstrument paymentInstrument)         
  29:      {             
  30:          var account = _accounts.Single(a => a.AccountID == accountId);             
  31:          var originalPi = account.PayinPIs.Single(p => p.PaymentInstrumentID == paymentInstrumentId);             
  32:          originalPi.FriendlyName = paymentInstrument.FriendlyName;             
  33:          return Ok(paymentInstrument);         
  34:      }         
  35:      // DELETE ~/Accounts(100)/PayinPIs(101)         
  36:      [ODataRoute("Accounts({accountId})/PayinPIs({paymentInstrumentId})")]         
  37:      public IHttpActionResult DeletePayinPIFromAccount(int accountId, int paymentInstrumentId)         
  38:      {             
  39:          var account = _accounts.Single(a => a.AccountID == accountId);             
  40:          var originalPi = account.PayinPIs.Single(p => p.PaymentInstrumentID == paymentInstrumentId);             
  41:          if (account.PayinPIs.Remove(originalPi))             
  42:          {                 
  43:              return StatusCode(HttpStatusCode.NoContent);             
  44:          }             
  45:          else             
  46:          {                 
  47:              return StatusCode(HttpStatusCode.InternalServerError);             
  48:          }         
  49:      }         
  50:      // GET ~/Accounts(100)/PayinPIs/Namespace.GetCount() 
  51:      [ODataRoute("Accounts({accountId})/PayinPIs/ODataContrainmentSample.GetCount(NameContains={name})")]         
  52:      public IHttpActionResult GetPayinPIsCountWhoseNameContainsGivenValue(int accountId, [FromODataUri]string name)         
  53:      {             
  54:          var account = _accounts.Single(a => a.AccountID == accountId);             
  55:          var count = account.PayinPIs.Where(pi => pi.FriendlyName.Contains(name)).Count();             
  56:          return Ok(count);         
  57:      }         
  58:      private static IList<Account> InitAccounts()         
  59:      {             
  60:          var accounts = new List<Account>() 
  61:          { 
  62:              new Account()                 
  63:              {                    
  64:                  AccountID = 100,                    
  65:                  Name="Name100",                    
  66:                  PayinPIs = new List<PaymentInstrument>()                     
  67:                  {                         
  68:                      new PaymentInstrument()                         
  69:                      {                             
  70:                          PaymentInstrumentID = 101,                             
  71:                          FriendlyName = "101 first PI",                         
  72:                      },                         
  73:                      new PaymentInstrument()                         
  74:                      {                             
  75:                          PaymentInstrumentID = 102,                             
  76:                          FriendlyName = "102 second PI",                         
  77:                      },                     
  78:                  },                 
  79:              },             
  80:          };            
  81:          return accounts;         
  82:      }     
  83:  }

If the OData path is 4 or more segments, only attribute routing works, such as [ODataRoute("Accounts({accountId})/PayinPIs({paymentInstrumentId})")] in the above controller. Otherwise, both attribute and conventional routing works: for instance, GetPayInPIs(int key) matches GET ~/Accounts(1)/PayinPIs.

Thanks to Leo Hu for the original content of this article.



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/odata-containment-in-web-api-22.htm
< THANKS ME>