Use of webAPi OData

Keywords: C# Database

1, Introduction to OData

Open Data Protocol (OData) is a description of how to create and access Restful Service OASIS Standard.

2, The usage of OData in asp.net mvc

1. Create a new webApi project in vs

2. Add test type

 public class Product
    {
        public int Id { get; set; }

        public string ProductName
        {
            get; set;
        }
    }

3. Enable EF automatic migration, add EF context,

namespace ODataTest.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using ODataTest.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<ODataTest.Models.EFContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(ODataTest.Models.EFContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.

        }
    }
}

 

 public class EFContext : DbContext
    {

        static EFContext()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFContext, Configuration>());
        }
        public EFContext() : base("DefaultConnection")
        {
        }

        public DbSet<Product> Products { get; set; }
    }

4. Add some test data to the database

Id ProductName
21 product 1
22 product 2
23 product 3
24 product 4

5. Add an OData controller to the Controllers folder

6. vs will automatically generate the basic CURD,

Set the AllowedQueryOptions property of the EnableQuery property of the GetProducts method to allow all queries AllowedQueryOptions.All

    public class ProductsController : ODataController
    {
        private EFContext db = new EFContext();

        // GET: odata/Products
        [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
        public IQueryable<Product> GetProducts()
        {
            return db.Products;
        }

        // GET: odata/Products(5)
        [EnableQuery]
        public SingleResult<Product> GetProduct([FromODataUri] int key)
        {
            return SingleResult.Create(db.Products.Where(product => product.Id == key));
        }

        // PUT: odata/Products(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta<Product> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Product product = db.Products.Find(key);
            if (product == null)
            {
                return NotFound();
            }

            patch.Put(product);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(product);
        }

        // POST: odata/Products
        public IHttpActionResult Post(Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Products.Add(product);
            db.SaveChanges();

            return Created(product);
        }

        // PATCH: odata/Products(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<Product> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Product product = db.Products.Find(key);
            if (product == null)
            {
                return NotFound();
            }

            patch.Patch(product);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(product);
        }

        // DELETE: odata/Products(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            Product product = db.Products.Find(key);
            if (product == null)
            {
                return NotFound();
            }

            db.Products.Remove(product);
            db.SaveChanges();

            return StatusCode(HttpStatusCode.NoContent);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool ProductExists(int key)
        {
            return db.Products.Count(e => e.Id == key) > 0;
        }
    }

 

7. Register OData route in the register method of WebApiConfig class

using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using ODataTest.Models;

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

8. Run the website and you can run the OData API test in the browser

Common queries:

Query all: http://localhost:64643/odata/Products

Query according to the primary key: http://localhost:64643/odata/Products(22) [22 is the primary key value]

Equivalent query: http: / / localhost: 64643 / OData / products? $filter = productnameeq 'product 1'

Query only some fields: http://localhost:64643/odata/Products?$select=Id

Fuzzy query (it's been searching for a long time): http: / / localhost: 64643 / OData / products? $filter = substring of ('product 1',ProductName) eq true

There are more queries, for reference, http://www.odata.org/documentation/odata-version-3-0/url-conventions/ The use of EF and OData in mvc can basically satisfy all front-end queries, which is conducive to the rapid development of API query interface

Posted by visualAd on Sun, 05 Apr 2020 02:45:59 -0700