在前两篇文章<Part I: Business Scenario> 和<Part II: Project Setup>后,可以开始真正Model的创建。

步骤如下:

1. 创建Models文件夹,并在该文件夹中加入一个数个Class。

Knowledge Category定义,代码如下:

using System;

namespace knowledgebuilderapi.Models {
public enum KnowledgeCategory: Int16 {
Concept = ,
Formula = ,
}
}

基类BaseModel,代码如下:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; namespace knowledgebuilderapi.Models {
public abstract class BaseModel { [Column("CreatedAt")]
public DateTime CreatedAt { get; set; }
[Column("ModifiedAt")]
public DateTime ModifiedAt { get; set; }
}
}

Knowledge的Model,代码如下:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; namespace knowledgebuilderapi.Models
{
[Table("Knowledge")]
public class Knowledge : BaseModel
{ [Key]
public Int32 ID { get; set; }
[Required]
[Column("ContentType")]
public KnowledgeCategory Category { get;set; }
[Required]
[MaxLength()]
[ConcurrencyCheck]
[Column("Title", TypeName = "NVARCHAR(50)")]
public string Title { get;set; }
[Required]
[Column("Content")]
public string Content { get;set; }
[Column("Tags")]
public string Tags { get; set; }
}
}

最后加入DataContext,代码如下:

using System;
using Microsoft.EntityFrameworkCore; namespace knowledgebuilderapi.Models
{
public class kbdataContext : DbContext
{
public kbdataContext(DbContextOptions<kbdataContext> options) : base(options)
{ } public DbSet<Knowledge> Knowledges { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Knowledge>()
.Property(b => b.CreatedAt)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<Knowledge>()
.Property(b => b.ModifiedAt)
.HasDefaultValueSql("getdate()");
modelBuilder.Entity<Knowledge>()
.Property(e => e.Category)
.HasConversion(
v => (Int16)v,
v => (KnowledgeCategory)v);
}
}
}

2. 如果Controller文件夹尚未创建,则创建一个,并在其中创建Knowledges的Controller

注意,由OData的命名规范来说,Controller的名字必须由[entityset]名字+Controller构成。参考文档:https://docs.microsoft.com/en-us/odata/webapi/built-in-routing-conventions

所以,如果在Edm的Model中定义了Knowledge,那么就需要定义KnowledgeController,

如果在Edm的Model中定义了Knowledges,那么就需要定义KnowledgesController。

完整代码如下:

using System;
using Microsoft.AspNet.OData;
using Microsoft.EntityFrameworkCore;
using knowledgebuilderapi.Models;
using System.Linq; namespace knowledgesbuilderapi.Controllers {
public class KnowledgesController : ODataController {
private readonly kbdataContext _context; public KnowledgesController(kbdataContext context)
{
_context = context;
} [EnableQuery]
public IQueryable<Knowledge> Get()
{
return _context.Knowledges;
}
}
}

3. 修改Startup

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNet.OData.Builder;
using Microsoft.AspNet.OData.Batch;
using knowledgebuilderapi.Models;
using Microsoft.AspNetCore.Routing; namespace knowledgebuilderapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; }
public string ConnectionString { get; private set; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
this.ConnectionString = Configuration["KBAPI.ConnectionString"]; services.AddDbContext<kbdataContext>(options =>
options.UseSqlServer(this.ConnectionString)); services.AddMvc(action => {
action.EnableEndpointRouting = false;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOData();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
} app.UseHttpsRedirection(); ODataModelBuilder modelBuilder = new ODataConventionModelBuilder(app.ApplicationServices);
modelBuilder.EntitySet<Knowledge>("Knowledges");
modelBuilder.Namespace = typeof(Knowledge).Namespace; var model = modelBuilder.GetEdmModel();
app.UseODataBatching(); app.UseMvc(routeBuilder =>
{
// and this line to enable OData query option, for example $filter
routeBuilder.Select().Expand().Filter().OrderBy().MaxTop().Count(); routeBuilder.MapODataServiceRoute("ODataRoute", "odata", model);
});
}
}
}

4. 在项目的根目录下执行

cd knowledgebuilderapi
dotnet run

5. 这时,打开浏览器,访问 http://localhost:5000/odata/$metadata

会成功拿到一下文件:

<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
<edmx:DataServices>
<Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="knowledgebuilderapi.Models">
<EntityType Name="Knowledge">
<Key>
<PropertyRef Name="ID"/>
</Key>
<Property Name="ID" Type="Edm.Int32" Nullable="false"/>
<Property Name="Category" Type="knowledgebuilderapi.Models.KnowledgeCategory" Nullable="false"/>
<Property Name="Title" Type="Edm.String" Nullable="false" MaxLength="50"/>
<Property Name="Content" Type="Edm.String" Nullable="false"/>
<Property Name="Tags" Type="Edm.String"/>
<Property Name="CreatedAt" Type="Edm.DateTimeOffset" Nullable="false"/>
<Property Name="ModifiedAt" Type="Edm.DateTimeOffset" Nullable="false"/>
</EntityType>
<EnumType Name="KnowledgeCategory" UnderlyingType="Edm.Int16">
<Member Name="Concept" Value="0"/>
<Member Name="Formula" Value="1"/>
</EnumType>
<EntityContainer Name="Container">
<EntitySet Name="Knowledges" EntityType="knowledgebuilderapi.Models.Knowledge">
<Annotation Term="Org.OData.Core.V1.OptimisticConcurrency">
<Collection>
<PropertyPath>Title</PropertyPath>
</Collection>
</Annotation>
</EntitySet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>

6. 如果数据库Connection String已经被正确维护在“KBAPI.ConnectionString”上的话,打开链接: ~/odata/Knowledges 将会看到数据。

创建基于OData的Web API - Knowledge Builder API, Part III:Write Model的更多相关文章

  1. 创建基于OData的Web API - Knowledge Builder API, Part IV: Write Controller

    基于上一篇<创建基于OData的Web API - Knowledge Builder API, Part III:Write Model and Controller>,新创建的ODat ...

  2. 创建基于OData的Web API - Knowledge Builder API, Part I:Business Scenario

    在.NET Core 刚刚1.0 RC的时候,我就给OData团队创建过Issue让他们支持ASP.NET Core,然而没有任何有意义的答复. Roadmap for ASP.NET Core 1. ...

  3. 创建基于OData的Web API - Knowledge Builder API, Part II:Project Setup

    本篇为Part II:Project Setup 查看第一篇<Part I:  Business Scenario> 第一步,准备步骤. 准备步骤一,下载.NET Core 2.2 SDK ...

  4. 使用 node-odata 轻松创建基于 OData 协议的 RESTful API

    前言 OData, 相信身为.NET程序员应该不为陌生, 对于他的实现, 之前也有童鞋进行过介绍(见:这里1,这里2). 微软的WCF Data Service即采用的该协议来进行通信, ASP.NE ...

  5. 基于SVG的web页面图形绘制API介绍

    转自:http://blog.csdn.net/jia20003/article/details/9185449 一:什么是SVG SVG是1999由W3C发布的2D图形描述语言,纯基于XML格式的标 ...

  6. Java Web学习系列——创建基于Maven的Web项目

    创建Maven Web项目 在MyEclipse for Spring中新建Maven项目 选择项目类型,在Artifact Id中选择maven-archetype-webapp 输入Group I ...

  7. 可能是最简单的方式:利用Eclipse创建基于Maven的Web项目

    1. 新建一个maven项目 2.在弹出框中选择创建一个简单项目 3. 然后输入参数,需要注意的是,在packagin中,选择war,web项目应该选择war 4. 点击finish后,基本项目结构就 ...

  8. idea创建基于maven的web项目

    1.点击create new project,选择maven,点击next 2.输入项目信息,点击finish 3.进入项目后,点击菜单File->Project Structure开始配置项目 ...

  9. maven-bundle-plugin插件, 用maven构建基于osgi的web应用

    maven-bundle-plugin 2.4.0以下版本导出META-INF中的内容到MANIFEST.MF中 今天终于把maven-bundle-plugin不能导出META-INF中的内容到Ex ...

随机推荐

  1. Windows常用操作

    目录 查询IP地址 常用快捷键 显示文件后缀名 查询IP地址 1.进入到dos界面 2.输入命令: ipconfig 常用快捷键 快捷键 作用 win+E 打开计算机 win+R 打开运行 win+R ...

  2. Python之装饰器(二)

    以前你有没有这样一段经历:很久之前你写过一个函数,现在你突然有了个想法就是你想看看,以前那个函数在你数据集上的运行时间是多少,这时候你可以修改之前代码为它加上计时的功能,但是这样的话是不是还要大体读读 ...

  3. JavaScript回调函数和递归函数

    一.回调函数--通过函数的指针来调用函数 把一个函数的指针作为另一个函数的参数,当调用这个参数的时候,这个函数就叫做回调函数 在链式运动上会用到回调函数,之后运动会见到 A.通过指针来调用函数 B.通 ...

  4. [NOIp2014] luogu P2296 寻找道路

    不知道是因为我菜还是别的,最近老是看错题. 题目描述 在有向图 GGG 中,每条边的长度均为 1,现给定起点和终点,请你在图中找一条从起点到终点的路径,该路径满足以下条件: 路径上的所有点的出边所指向 ...

  5. nginx::certbot制作免费证书

    环境 Ubuntu8.04apt-get update apt-get install software-properties-common add-apt-repository ppa:certbo ...

  6. docker3-镜像的使用

    基本使用命令: [root@ipha-dev71- docker]# docker search python # 搜索镜像 [root@ipha-dev71- docker]# docker pul ...

  7. Dell R720 RAID配置

    Dell服务器上一般都带有Raid卡,Raid5配置请看下边,亲们 1. 将服务器接上电源,显示器,键盘,并开机 2. 按 ctrl + R进入Raid设置 3. 将光标放置在Raid卡那,按F2,选 ...

  8. 备战双 11!蚂蚁金服万级规模 K8s 集群管理系统如何设计?

    作者 | 蚂蚁金服技术专家 沧漠 关注『阿里巴巴云原生』公众号,回复关键词"1024",可获取本文 PPT. 前言 Kubernetes 以其超前的设计理念和优秀的技术架构,在容器 ...

  9. 安装配置 Android Studio

    概述 Android Studio 本身应该是开箱即用的,但是由于 dl.google.com 访问太慢,导致了这样那样的问题,因此我们只需要改一下 hosts 就行了 具体步骤 在Ping检测网站查 ...

  10. 百万年薪python之路 -- 面向对象之三大特性

    1.面向对象之三大特性 1.1封装 封装:就是把一堆代码和数据,放在一个空间,并且可以使用 对于面向对象的封装来说,其实就是使用构造方法将内容封装到 对象 中,然后通过对象直接或者self间接获取被封 ...