Coder Social home page Coder Social logo

alanlisboa / xpo-json-serialization Goto Github PK

View Code? Open in Web Editor NEW

This project forked from biohazard999/xpo-json-serialization

0.0 0.0 0.0 25 KB

Demonstrates how to use the persistent object JSON serialization feature

License: Other

C# 100.00%

xpo-json-serialization's Introduction

An ASP.NET Core Web API CRUD Service

When building a Web API service, it is convenient to separate your Controller's code from the data access logic. Don't deal with SQL, DB connections, etc. each time you need to extend your API, but use the database-independent object-oriented approach to retrieve data with sorting, filtering and complex data shaping.

The persistent object JSON serialization feature makes it easy to use XPO as a Data Access layer in an ASP.NET Core Web API service. You no longer need to manually format JSON responses or make a POCO copy of each persistent class. This tutorial demonstrates how to enable this feature and implement a few Controllers.

You may also be interested in the following examples:

Prerequisites

Visual Studio 2017 version 15.2.7 ot later with the following workloads:

Create the project.

Use the following steps to create a project or refer to the original tutorial in the Microsoft documentation.

  • From the File menu, select New > Project.
  • Select the ASP.NET Core Web Application template. Fill in the Name field and click the OK button.
  • In the New ASP.NET Core Web Application - [YourProjectName] dialog, choose the ASP.NET Core version. Select the API template and click OK.

Configure XPO

  • Install DevExpress.XPO Nuget package.
    Install-Package DevExpress.Xpo
  • Use the ORM Data Model Wizard to create the data model or generate it from the existing database. This step is required, because the ORM Data Model Wizard adds extension methods that will be used later in this tutorial.
  • Add the connection string to the appsettings.json file.
"ConnectionStrings": {
  "SQLite": "XpoProvider=SQLite;Data Source=demo.db",
  "MSSqlServer": "XpoProvider=MSSqlServer;data source=(local);user id=sa;password=;initial catalog=XpoASPNETCoreDemo;Persist Security Info=true"
}
  • Open the Startup.cs file and register the UnitOfWork Service as described in ASP.NET Core Dependency Injection in XPO.
    public void ConfigureServices(IServiceCollection services) {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      services.AddXpoDefaultUnitOfWork(true, (DataLayerOptionsBuilder options) =>
          options.UseConnectionString(Configuration.GetConnectionString("MsSqlServer"))
          .UseEntityTypes((ConnectionHelper.GetPersistentTypes()));
    }
  • Call the Add[YourXPOModelName]SerializationOptions extension method to enable the JSON serialization support.
public void ConfigureServices(IServiceCollection services) {
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
       .AddDxSampleModelJsonOptions();
// ..

Create a Controller

  • Declare a local variable to store the UnitOfWork instance passed as a constructor parameter.
[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase {
   private UnitOfWork uow;
   public CustomersController(UnitOfWork uow) {
   	this.uow = uow;
   }
  • GET methods implementation is simple and straightforward. Load object(s) from the database and return the result.
[HttpGet]
public IEnumerable Get() {
   return uow.Query<Customer>();
} 
[HttpGet("{id}")]
public Customer Get(int id) {
   return uow.GetObjectByKey<Customer>(id);
}
  • The POST method creates a new persistent object and saves it to the database. To parse JSON data, declare a method parameter of the JObject type.
[HttpPost]
public void Post([FromBody]JObject values) {
   Customer customer = new Customer(uow);
   customer.ContactName = values["ContactName"].Value<string>();
   uow.CommitChanges();
}
  • The PUT and DELETE methods do not require any special remarks.
[HttpPut("{id}")]
public void Put(int id, [FromBody]JObject value) {
   Customer customer = uow.GetObjectByKey<Customer>(id);
   customer.ContactName = value["ContactName"].Value<string>();
   uow.CommitChanges();
}
[HttpDelete("{id}")]
public void Delete(int id) {
   Customer customer = uow.GetObjectByKey<Customer>(id);
   uow.Delete(customer);
   uow.CommitChanges();
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.