使用Entity Framework类库,可以在Tools|NuGet Package Manager|Manage NuGetPackages for Solution中搜索安装,
示例代码如下:
using System.Linq:
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
- public class Book //Book类,包含三个属性
- {
- public string Title { get; set; }
- public string Author { get; set; }
- [Key] public int Code { get; set; } //[Key]特性把 Code属性识别为数据库中每一行的唯一标识
- }
- public class BookContext : DbContext //BookContext继承DbContext(数据库上下文)用于创建,更新,删除数据库
- {
- public DbSet<Book> Books { get; set; } //数据库中的book对象集合
- }
- class Program
- {
- static void Main(string[] args)
- {
- using (var db = new BookContext())
- {
- //添加两个对象到数据库中
- Book book1 = new Book { Title = "Beginning Visual C# 2015", Author = "Ben" };
- AddBook(db, book1);
- book2 = new Book { Title = "Beginning XML", Author = "Gen"};
- AddBook(db, book2);
- //Linq查询
- var query = from b in db.Books
- orderby b.Title //排序
- select b;
- WriteLine("All books in the database:");
- //foreach循环输出
- foreach (var b in query)
- {
- WriteLine($"{b.Title} by {b.Author}, code={b.Code}");
- }
- }
- }
- //添加到数据库的方法
- private static void AddBook(BookContext db, Book book)
- {
- var testQuery = from b in db.Books
- where b.Title == book.Title && b.Author == book.Author
- select b;
- if (testQuery.Count() < 1)
- {
- db.Books.Add(book); //添加
- db.SaveChanges(); //保存
- }
- }
- }