在前两篇文章<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. [Quarks PwDump]Hash dump神器

    好不好用就不用说了哈  记录下使用方式 也支持导出本地哈希.域控哈希等.配合hashcat神器 奇效. 它目前可以导出 : – Local accounts NT/LM hashes +history ...

  2. window 下Notepad++设置为文本文件的默认打开程序失败

    1.右键Notepad++的可执行程序,选择"属性"  -- "兼容性" , 设置Notepad++以管理员的身份运行 2.打开Notepad++ ," ...

  3. ‎Cocos2d-x 学习笔记(26) 从源码学习 DrawCall 的降低方法

    [Cocos2d-x]学习笔记目录 本文链接:https://www.cnblogs.com/deepcho/cocos2dx-drawcall-glcalls 1. 屏幕左下角 我们通常在Cocos ...

  4. win10系统plsql卡顿、菜单闪烁解决办法

    右键快捷方式--属性--兼容性: 设置为以win7模式运行,以管理员模式运行.如图:

  5. boost::multi_index 多索引容器

    #include "stdafx.h" #include <string> #include <boost/multi_index_container.hpp&g ...

  6. 【OUC2019写作】学术论文写作第九小组第一次博客作业

    个人简介 潘旻琦:我是潘旻琦:我的爱好是游泳:羊肉泡馍是海大食堂中我最喜欢的一道菜(清真食堂):一句想说的话是:“追随本心,坚持不懈”. 郭念帆:我是郭念帆:我的爱好是足球:海大食堂中最喜欢的一道菜偏 ...

  7. CheckBox多选

    前台: <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> & ...

  8. MySql悲观锁与乐观锁区别及使用场景

    一.概念上的区别 乐观锁( Optimistic Locking):顾名思义,对加锁持有一种乐观的态度,即先进行业务操作,不到最后一步不进行加锁,"乐观"的认为加锁一定会成功的,在 ...

  9. [转载]制作QT字库文件

    原文地址:http://www.cnblogs.com/liu_xf/archive/2011/07/05/2098144.htm 摘要: QT4.7.0在移植到开发板上的时候,中文支持是必不可少的, ...

  10. MacOS 系统 文件夹解析

    Mac OS X,基于UNIX核心的系统,增强了系统的稳定性.性能以及响应能力. 通过对称多处理技术充分发挥双处理器的优势,提供无与伦比的2D.3D和多媒体图形性能以及广泛的字体支持和集成的PDA功能 ...