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

Part 2: Creating the Domain Models

by Mike Wasson

Download Completed Project

Add Models

There are three ways to approach Entity Framework:

We are using the code-first approach, so we start by defining our domain objects as POCOs (plain-old CLR objects). With the code-first approach, domain objects don’t need any extra code to support the database layer, such as transactions or persistence. (Specifically, they do not need to inherit from the EntityObject class.) You can still use data annotations to control how Entity Framework creates the database schema.

Because POCOs do not carry any extra properties that describe database state, they can easily be serialized to JSON or XML. However, that does not mean you should always expose your Entity Framework models directly to clients, as we’ll see later in the tutorial.

We will create the following POCOs:

To create each class, right-click the Models folder in Solution Explorer. From the context menu, select Add and then select Class.

Add a Product class with the following implementation:

[!code-csharpMain]

   1:  namespace ProductStore.Models
   2:  {
   3:      using System.ComponentModel.DataAnnotations;
   4:   
   5:      public class Product
   6:      {
   7:          [ScaffoldColumn(false)]
   8:          public int Id { get; set; }
   9:          [Required]
  10:          public string Name { get; set; }
  11:          public decimal Price { get; set; }
  12:          public decimal ActualCost { get; set; }
  13:      }
  14:  }

By convention, Entity Framework uses the Id property as the primary key and maps it to an identity column in the database table. When you create a new Product instance, you won’t set a value for Id, because the database generates the value.

The ScaffoldColumn attribute tells ASP.NET MVC to skip the Id property when generating an editor form. The Required attribute is used to validate the model. It specifies that the Name property must be a non-empty string.

Add the Order class:

[!code-csharpMain]

   1:  namespace ProductStore.Models
   2:  {
   3:      using System.Collections.Generic;
   4:      using System.ComponentModel.DataAnnotations;
   5:   
   6:      public class Order
   7:      {
   8:          public int Id { get; set; }
   9:          [Required]
  10:          public string Customer { get; set; }
  11:   
  12:          // Navigation property
  13:          public  ICollection<OrderDetail> OrderDetails { get; set; }
  14:      }
  15:  }

Add the OrderDetail class:

[!code-csharpMain]

   1:  namespace ProductStore.Models
   2:  {
   3:      public class OrderDetail
   4:      {
   5:          public int Id { get; set; }
   6:          public int Quantity { get; set; }
   7:          public int OrderId { get; set; }
   8:          public int ProductId { get; set; }
   9:   
  10:          // Navigation properties
  11:          public Product Product { get; set; }
  12:          public Order Order { get; set; }
  13:      }
  14:  }

Foreign Key Relations

An order contains many order details, and each order detail refers to a single product. To represent these relations, the OrderDetail class defines properties named OrderId and ProductId. Entity Framework will infer that these properties represent foreign keys, and will add foreign-key constraints to the database.

The Order and OrderDetail classes also include “navigation” properties, which contain references to the related objects. Given an order, you can navigate to the products in the order by following the navigation properties.

Compile the project now. Entity Framework uses reflection to discover the properties of the models, so it requires a compiled assembly to create the database schema.

Configure the Media-Type Formatters

A media-type formatter is an object that serializes your data when Web API writes the HTTP response body. The built-in formatters support JSON and XML output. By default, both of these formatters serialize all objects by value.

Serialization by value creates a problem if an object graph contains circular references. That’s exactly the case with the Order and OrderDetail classes, because each holds a reference to the other. The formatter will follow the references, writing each object by value, and go in circles. Therefore, we need to change the default behavior.

In Solution Explorer, expand the App_Start folder and open the file named WebApiConfig.cs. Add the following code to the WebApiConfig class:

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          config.Routes.MapHttpRoute(
   6:              name: "DefaultApi",
   7:              routeTemplate: "api/{controller}/{id}",
   8:              defaults: new { id = RouteParameter.Optional }
   9:          );
  10:   
  11:          // New code:
  12:          var json = config.Formatters.JsonFormatter;
  13:          json.SerializerSettings.PreserveReferencesHandling =
  14:              Newtonsoft.Json.PreserveReferencesHandling.Objects;
  15:   
  16:          config.Formatters.Remove(config.Formatters.XmlFormatter);
  17:      }
  18:  }

This code sets the JSON formatter to preserve object references, and removes the XML formatter from the pipeline entirely. (You can configure the XML formatter to preserve object references, but it’s a little more work, and we only need JSON for this application. For more information, see Handling Circular Object References.)

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/older-versions/using-web-api-1-with-entity-framework-5/using-web-api-with-entity-framework-part-2.htm
< THANKS ME>