Skip to content

develop

moh-hassan edited this page Dec 15, 2021 · 3 revisions

Odata2Poco class library is provided as:

  • NET50
  • Netstandard2.0
  • NET45
  • NET461

To start developing using the Class Library OData2Poco using C# and VS2017, download the demo project install the class library using the command:

    Install-Package OData2Poco -Version 3.5.0 

Note: The class library is hosted in the nuget Gallery

  • Define the OdataConnectionString

         var connString = new OdataConnectionString
          {
              ServiceUrl = "http://services.odata.org/V4/OData/OData.svc",
              Authenticate = AuthenticationType.None,
          };
    
  • Define the PocoSetting

         var setting = new PocoSetting
          {
              Attributes = new List<string> { "key"},
              AddNavigation = true,
              AddNullableDataType = true,
          };
    
  • Generate c# code:

             var o2p = new O2P(setting);
              var code = await o2p.GenerateAsync(connString);
    

The complete source code is:

Click to expand!
internal class Program
{
static async Task Main(string[] args)
{
    Console.WriteLine("Hello OData2Poco Demo!");
    // string client_id="<Enter client id /or application id here>";
    // string client_secret="<Enter client secret  here>";

    //define connection parameters
    var connString = new OdataConnectionString
    {
        ServiceUrl = "http://services.odata.org/V4/OData/OData.svc",
        Authenticate = AuthenticationType.None,

        //for oauth2
        //Authenticate = AuthenticationType.oauth2,
        //UserName = client_id,  
        //Password = client_secret,  
        //TokenParams = "resource=...",
        //TokenUrl = "https://url/of/tokenserver",
        
    };
    var setting = new PocoSetting
    {
        Attributes = new List<string> { "key"},
        AddNavigation = true,
        AddNullableDataType = true,
    };

    try
    {
        var o2p = new O2P(setting);
        var code = await o2p.GenerateAsync(connString);
        Console.WriteLine(code);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }            
    
  }
}

Sample of output

Click to expand!
Hello World!
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated using  OData2Poco System.
//     Service Url: http://services.odata.org/V4/OData/OData.svc
//     MetaData Version: 4.0
//     Generated On: 2021-08-28T11:53:23
//     Parameters:

// </auto-generated>
//------------------------------------------------------------------------------


using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.Spatial;

namespace ODataDemo
{
        public partial class Product
        {
            [Key]
            public virtual int ID {get;set;} //PrimaryKey not null

            public virtual string Name {get;set;}

            public virtual string Description {get;set;}

            public virtual DateTimeOffset ReleaseDate {get;set;} // not null

            public virtual DateTimeOffset? DiscontinuedDate {get;set;}

            public virtual short Rating {get;set;} // not null

            public virtual double Price {get;set;} // not null

            public virtual List<Category> Categories {get;set;}

            public virtual Supplier Supplier {get;set;}

            public virtual ProductDetail ProductDetail {get;set;}

        }

        public partial class FeaturedProduct : Product
        {
            public virtual Advertisement Advertisement {get;set;}

        }

        public partial class ProductDetail
        {
            [Key]
            public virtual int ProductID {get;set;} //PrimaryKey not null

            public virtual string Details {get;set;}

            public virtual Product Product {get;set;}

        }

        public partial class Category
        {
            [Key]
            public virtual int ID {get;set;} //PrimaryKey not null

            public virtual string Name {get;set;}

            public virtual List<Product> Products {get;set;}

        }

        public partial class Supplier
        {
            [Key]
            public virtual int ID {get;set;} //PrimaryKey not null

            public virtual string Name {get;set;}

            public virtual Address Address {get;set;}

            public virtual GeographyPoint Location {get;set;}

            public virtual int Concurrency {get;set;} // not null

            public virtual List<Product> Products {get;set;}

        }

        public partial class Address
        {
            public virtual string Street {get;set;}

            public virtual string City {get;set;}

            public virtual string State {get;set;}

            public virtual string ZipCode {get;set;}

            public virtual string Country {get;set;}

        }

        public partial class Person
        {
            [Key]
            public virtual int ID {get;set;} //PrimaryKey not null

            public virtual string Name {get;set;}

            public virtual PersonDetail PersonDetail {get;set;}

        }

        public partial class Customer : Person
        {
            public virtual decimal TotalExpense {get;set;} // not null

        }

        public partial class Employee : Person
        {
            public virtual long EmployeeID {get;set;} // not null

            public virtual DateTimeOffset HireDate {get;set;} // not null

            public virtual float Salary {get;set;} // not null

        }

        public partial class PersonDetail
        {
            [Key]
            public virtual int PersonID {get;set;} //PrimaryKey not null

            public virtual byte Age {get;set;} // not null

            public virtual bool Gender {get;set;} // not null

            public virtual string Phone {get;set;}

            public virtual Address Address {get;set;}

            public virtual Stream Photo {get;set;} // not null

            public virtual Person Person {get;set;}

        }

        public partial class Advertisement
        {
            [Key]
            public virtual Guid ID {get;set;} //PrimaryKey not null

            public virtual string Name {get;set;}

            public virtual DateTimeOffset AirDate {get;set;} // not null

            public virtual FeaturedProduct FeaturedProduct {get;set;}

        }

}
 

Try OData2Poco online

Renaming Classes and Properties

You can rename the generated classes and their properties using json data.

The next Example show how to rename:

Click to expand!
using System;
using System.IO;
using System.Threading.Tasks;
using OData2Poco;
using OData2Poco.Api;
using OData2Poco.Extensions;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("Hello World");
			var c = new NameMappingTest();
	c.NameMapping().Wait();

	}
}
 
    public class NameMappingTest
    {
		//rename properties and classes based on json file
	string json =@"
{
  ClassNameMap: [
    {
      OldName: 'City',
      NewName: 'a0_City'
    },
    {
      OldName: 'Location',
      NewName: 'a0_Location'
    }
  ],
  PropertyNameMap: {
    City: [
      {
        OldName: 'Name',
        NewName: 'f02_Name'
      }
    ]
  }
}
";

        string _url = "https://services.odata.org/TripPinRESTierService";
        private OdataConnectionString _connString;
         
        async Task<string> Generate(string json)
        {
		 _connString = new OdataConnectionString { ServiceUrl = _url };            
            var setting = new PocoSetting
            {
                RenameMap = json.ToObject<RenameMap>(),
            };
            var o2P = new O2P(setting);
            var code = await o2P.GenerateAsync(_connString);
            return code;
        }
        
        public async Task NameMapping()
        {
            var code = await Generate(json);
			Console.WriteLine(code);
            
        }
 		
    }

Ouput

Click to expand!
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated using  OData2Poco System.
//     Service Url: https://services.odata.org/TripPinRESTierService
//     MetaData Version: 4.0
//     Generated On: 2021-12-14T23:48:40
//     Parameters:

// </auto-generated>
//------------------------------------------------------------------------------


using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Spatial;

namespace Trippin
{
  public partial class Person
  {
      public string UserName {get;set;} //PrimaryKey not null

      public string FirstName {get;set;} // not null

      public string LastName {get;set;}

      public string MiddleName {get;set;}

      public PersonGender Gender {get;set;} // not null

      public long Age {get;set;}

      public List<string> Emails {get;set;}

      public List<a0_Location> AddressInfo {get;set;}

      public a0_Location HomeAddress {get;set;}

      public Feature FavoriteFeature {get;set;} // not null

      public List<Feature> Features {get;set;} // not null

  }

  public partial class Airline
  {
      public string AirlineCode {get;set;} //PrimaryKey not null

      public string Name {get;set;}

  }

  public partial class Airport
  {
      public string Name {get;set;}

      public string IcaoCode {get;set;} //PrimaryKey not null

      public string IataCode {get;set;}

      public AirportLocation Location {get;set;}

  }

  public partial class a0_Location
  {
      public string Address {get;set;}

      public a0_City City {get;set;}

  }

  public partial class a0_City
  {
      public string f02_Name {get;set;}

      public string CountryRegion {get;set;}

      public string Region {get;set;}

  }

  public partial class AirportLocation : a0_Location
  {
      public GeographyPoint Loc {get;set;}

  }

  public partial class EventLocation : a0_Location
  {
      public string BuildingInfo {get;set;}

  }

  public partial class Trip
  {
      public int TripId {get;set;} //PrimaryKey not null

      public Guid ShareId {get;set;} // not null

      public string Name {get;set;}

      public float Budget {get;set;} // not null

      public string Description {get;set;}

      public List<string> Tags {get;set;}

      public DateTimeOffset StartsAt {get;set;} // not null

      public DateTimeOffset EndsAt {get;set;} // not null

  }

  public partial class PlanItem
  {
      public int PlanItemId {get;set;} //PrimaryKey not null

      public string ConfirmationCode {get;set;}

      public DateTimeOffset StartsAt {get;set;} // not null

      public DateTimeOffset EndsAt {get;set;} // not null

      public TimeSpan Duration {get;set;} // not null

  }

  public partial class Event : PlanItem
  {
      public EventLocation OccursAt {get;set;}

      public string Description {get;set;}

  }

  public partial class PublicTransportation : PlanItem
  {
      public string SeatNumber {get;set;}

  }

  public partial class Flight : PublicTransportation
  {
      public string FlightNumber {get;set;}

  }

  public partial class Employee : Person
  {
      public long Cost {get;set;} // not null

  }

  public partial class Manager : Person
  {
      public long Budget {get;set;} // not null

      public a0_Location BossOffice {get;set;}

  }

  public enum PersonGender
   {
     Male=0,
    Female=1,
    Unknown=2
  }
  public enum Feature
   {
     Feature1=0,
    Feature2=1,
    Feature3=2,
    Feature4=3
  }
}

Try it online

Generating code using T4 Template

A T4 template is included in the demo project.

Configure the connection parameters and PocoSetting as above.

Clone this wiki locally