ASP.NET Core EF Sample

Install EF


Install-Package Microsoft.EntityFrameworkCore.SqlServer 


Install-Package Microsoft.EntityFrameworkCore.Tools –Pre 

创建模型

创建Blog,Post模型

namespace EFGetStarted.AspNetCore.NewDb.Models
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }

        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

    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; }
    }
}

DI


public void ConfigureServices(IServiceCollection services) { 

    var connection = @"Server=(localdb)mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;"; 

    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

创建数据库


Add-Migration MyFirstMigration -context BloggingContext

Update-Database -context BloggingContext

创建一个Controller,View

按照模块创建即可测试。

Ref:https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html

原文地址:https://www.cnblogs.com/pengzhen/p/5760103.html