模型查詢和儲存資料
模型
使用 EF Core,可以使用模型執行資料訪問。模型由實體類和派生上下文組成,表示與資料庫的會話,允許你查詢和儲存資料。
你可以從現有資料庫生成模型,手動編寫模型以匹配資料庫,或使用 EF 遷移從模型建立資料庫(並隨著模型的變化隨時間變化而演變)。
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=MyDatabase;Trusted_Connection=True;");
}
}
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; }
}
}
查詢
使用語言整合查詢(LINQ)從資料庫中檢索實體類的例項。
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();
}
刪除資料
使用語言整合查詢(LINQ)從資料庫中檢索實體類的例項。
using (var db = new BloggingContext())
{
var blog = new Blog { Url = "http://sample.com" };
db.Blogs.Attach(blog);
db.Blogs.Remove(blog);
db.SaveChanges();
}
更新資料
使用實體類的例項在資料庫中更新資料。
using (var db = new BloggingContext())
{
var blog = new Blog { Url = "http://sample.com" };
var entity = db.Blogs.Find(blog);
entity.Url = "http://sample2.com";
db.SaveChanges();
}