Fork me on GitHub

ASP.NET Core 1.0 中 EntityFramework 与 PostgreSQL 的使用

https://docs.efproject.net/en/latest/providers/npgsql/index.html

前面在CentOS6.7环境下配置好了PostgreSQL, 就顺便试了一下 ASP.NET Core 1.0 环境下EF与PostgreSQL的使用,就是.NET Core 还不支持CentOS,要么就可以部署一下试试。

依赖包

复制代码
"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework7.Npgsql": "3.1.0-rc1-3",
    "EntityFramework7.Npgsql.Design": "3.1.0-rc1-5"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel",
    "ef": "EntityFramework.Commands"
  },
复制代码

CODE FISRT

复制代码
public class StockHqDbContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Make Blog.Url required
            modelBuilder.Entity<Blog>()
                        .Property(b => b.Url)
                        .IsRequired();
        }
    }
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public List<Post> Posts { get; set; }
    }
   public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
复制代码

注册PostgreSqlProvider

复制代码
public void ConfigureServices(IServiceCollection services)
        {
            var connection = Configuration["PostgreSqlProvider:ConnectionString"];
            services.AddEntityFramework()
                    .AddNpgsql()
                    .AddDbContext<StockHqDbContext>(options => options.UseNpgsql(connection));
            // Add framework services.
            services.AddMvc();
        }
复制代码

配置文件

复制代码
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "PostgreSqlProvider": {
    "ConnectionString": "User ID=postgres;Password=xxxxx;Host=xxx.xxx.xxx.xxx;Port=5432;Database=stockhq;Pooling=true;"
  }
}
复制代码

执行命令

dnvm use 1.0.0-rc1-final(dnvm install 1.0.0-rc1-final) 
dnx ef migrations add FirstMigration 
dnx ef database update

构造页面

复制代码
public class BlogsController : Controller
    {
        private StockHqDbContext _context;

        public BlogsController(StockHqDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(_context.Blogs.ToList());
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Blogs.Add(blog);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(blog);
        }

    }
复制代码

视图

复制代码
@model IEnumerable<StockHq.Models.Blog>
@{
    ViewBag.Title = "Blogs";
}
<h2>Blogs</h2>
<p>
    <a asp-controller="Blogs" asp-action="Create">Create New</a>
</p>
<table class="table">
    <tr>
        <th>Id</th>
        <th>Url</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.BlogId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Url)
            </td>
        </tr>
    }
</table>

@model StockHq.Models.Blog
@{
    ViewBag.Title = "New Blog";
}
<h2>@ViewData["Title"]</h2>
<form asp-controller="Blogs" asp-action="Create" method="post" class="form-horizontal" role="form">
    <div class="form-horizontal">
        <div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Url" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="Url" class="form-control" />
                <span asp-validation-for="Url" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>
复制代码

访问:http://localhost:49648/Blogs/Create 增加数据,完事,睡觉。

image

REFER:
http://dotnet.github.io/getting-started
https://github.com/aspnet/EntityFramework
https://github.com/npgsql/npgsql
.NET跨平台:在Linux上基于ASP.NET 5用EF7生成数据库
http://www.cnblogs.com/dudu/p/4621933.html
十分钟轻松让你认识Entity Framework 7
http://www.cnblogs.com/n-pei/p/4274907.html

posted @   花儿笑弯了腰  阅读(1236)  评论(4编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示