Use of webAPi OData and webAPiOData

Source: Internet
Author: User

Use of webAPi OData and webAPiOData
I. Introduction to OData

Open Data Protocol (OData) is an OASIS standard that describes how to create and access Restful services.

Ii. Usage of OData in asp.net mvc 1. Create a webApi project in


2. Add a test Type
 public class Product
    {
        public int Id { get; set; }

        public string ProductName
        {
            get; set;
        }
    }
3. Enable Automatic EF migration and 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
Product 4

5. Add an OData controller to the Controllers folder.


6. vs automatically generates the basic CURD,

Set the AllowedQueryOptions attribute of the EnableQuery feature of the GetProducts method to allow All queries to 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 the OData route in the Register Method of the 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 to test the OData API in the browser.

Common query:

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

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

Equality query: http: // localhost: 64643/odata/Products? $ Filter = ProductName eq 'product 1'

Only query partial fields: http: // localhost: 64643/odata/Products? $ Select = Id

Fuzzy query (this has been found for a long time): http: // localhost: 64643/odata/Products? $ Filter = substringof ('product 1', ProductName) eq true

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


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.