在前两篇文章<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. Java表达式计算转型规则

    本题答案应为:B.C.D ------------知识点------------ Java表达式转型规则由低到高转换(例如int 到 double): 1.所有的byte,short,char型的值将 ...

  2. Vue中组件

    0828自我总结 Vue中组件 一.组件的构成 组件:由 template + css + js 三部分组成(.vue文件) 1)组件具有复用性 2) 复用组件时,数据要隔离 3) 复用组件时,方法不 ...

  3. QT文件读写操作笔记

    补一下这部分的笔记 简单的东西也记一下 操作系统一般都会提供一些列的标准对话框,如文件选择.字体选择.颜色选择等,这些标准对话框为应用层序提供了一致的观感.Qt对这些标准对话框都定义了相关的类,如:Q ...

  4. cobalt strike和metasploit结合使用(互相传递shell会话

    攻击机 192.168.5.173 装有msf和cs 受害机 192.168.5.179 win7 0x01 msf 派生 shell 给 Cobalt strike Msfvenom生成木马上线: ...

  5. 爬虫3:html页面+webdriver模块+demo

    保密性好的网站,不能使用request请求页面信息,这样可以使用webdriver模块先开启一个浏览器,然后爬去信息,甚至还可以click等操作对页面操作,再爬取. demo 一般流程: 1)包含se ...

  6. 数据挖掘:python数据清洗cvs里面带中文字符

    数据清洗,使用python数据清洗cvs里面带中文字符,意图是用字典对应中文字符,即key值是中文字符,value值是index,自增即可:利用字典数据结构没有重复key值的特性,把中文字符映射到了数 ...

  7. [JZOJ5185] 【NOIP2017提高组模拟6.30】tty's sequence

    Description

  8. 关于_GNU_SOURCE宏

    是在features.h中用于特性控制的一个功能测试宏 /user/include/features.h /* If _GNU_SOURCE was defined by the user, turn ...

  9. std::weak_ptr

    weak_ptr 是一种不控制对象生命周期的智能指针, 它指向一个 shared_ptr 管理的对象. 进行该对象的内存管理的是那个强引用的 shared_ptr. weak_ptr只是提供了对管理对 ...

  10. django2-创建项目

    方式一:cmd或linux命令行下创建django项目(不常用,此处不做详细介绍) django-admin.py startproject autotest 方式二:使用pycharm专业版创建dj ...