在前两篇文章<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. Oracle11g安装与基本使用

    目录 安装 修改用户密码 配置文件修改 使用PLSQL连接Oracle数据库 如何执行SQL 语句 本教程基于oracle11g和PLSQL进行 下载资源见百度网盘链接:https://pan.bai ...

  2. wireshark分析https

    0x01 分析淘宝网站的https数据流 打开淘宝 wireshark抓取到如下 第一部分: 因为https是基于http协议上的,可以看到首先也是和http协议一样的常规的TCP三次握手的连接建立, ...

  3. opencv::自定义线性滤波

    卷积概念 常见算子 自定义卷积模糊 卷积概念 1.卷积是图像处理中一个操作,是kernel在图像的每个像素上的操作. 2.Kernel本质上一个固定大小的矩阵数组,其中心点称为锚点(anchor po ...

  4. java学习-IDEA相关使用

    1.配置git与github(用于将代码提交到GitHub) 添加自己的github账号 2.提交代码到github 登录https://github.com,即可看到刚刚提交到github的代码仓库 ...

  5. Windows下Python虚拟环境的配置

    一.了解Python虚拟环境 所谓虚拟环境可以理解为不同的不连通的本地设备,打个比方就是在一台电脑上能做到多台电脑能做的事情. 例如:现在我们有两个项目需要不同的配置,记为A项目需要库a------- ...

  6. C语言1博客作业03

    这个作业属于哪个课程 C语言程序设计1 这个作业要求在哪里 (https://edu.cnblogs.com) 我在这个课程的目标是 掌握函数运算 我在这个作业哪个具体方面帮助实现目标 编译一些基本生 ...

  7. SpringBoot系列教程之Bean加载顺序之错误使用姿势辟谣

    在网上查询 Bean 的加载顺序时,看到了大量的文章中使用@Order注解的方式来控制 bean 的加载顺序,不知道写这些的博文的同学自己有没有实际的验证过,本文希望通过指出这些错误的使用姿势,让观文 ...

  8. 设置和获取html里面的内容.html

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. spring boot项目启动报错

    在eclipse中运行没有任何问题,项目挪到idea之后就报错 Unable to start EmbeddedWebApplicationContext due to miss EmbeddedSe ...

  10. Python的闭包以及迭代器

    一,闭包 什么是闭包呢?闭包就是内层函数,对外层函数(非外层)的变量的引用,叫做闭包 def mz(): name = 'YJ' def xue(): print(name) #闭包 xue() mz ...