1.NuGet安装 entity-framework-core
2.创建DB上下文和Model类。
using Microsoft.EntityFrameworkCore; using System.Collections.Generic; namespace Intro { public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer( @"Server=(localdb)mssqllocaldb;Database=Blogging;Integrated Security=True"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public int Rating { 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; } } }
查询
using (var db = new BloggingContext()) { var blogs = db.Blogs .Where(b => b.Rating > 3) .OrderBy(b => b.Url) .ToList(); }
保存数据
using (var db = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; db.Blogs.Add(blog); db.SaveChanges(); }