C#基础:数据库

        使用Entity Framework类库,可以在Tools|NuGet Package Manager|Manage NuGetPackages for Solution中搜索安装,

示例代码如下:

using System.Linq:

using System.Data.Entity;

using System.ComponentModel.DataAnnotations;

  1. public class Book                //Book类,包含三个属性
  2.     {
  3.         public string Title { get; set; }
  4.         public string Author { get; set; }
  5.         [Key]  public int Code { get; set; }     //[Key]特性把 Code属性识别为数据库中每一行的唯一标识
  6.     }
  7.     public class BookContext : DbContext     //BookContext继承DbContext(数据库上下文)用于创建,更新,删除数据库
  8.     {
  9.         public DbSet<Book> Books { get; set; }   //数据库中的book对象集合
  10.     }
  11.     class Program
  12.     {
  13.         static void Main(string[] args)
  14.         {
  15.             using (var db = new BookContext())
  16.             {
  17.                //添加两个对象到数据库中
  18.                 Book book1 = new Book { Title = "Beginning Visual C# 2015", Author = "Ben" };
  19.                 AddBook(db, book1);
  20.                 book2 = new Book { Title = "Beginning XML", Author = "Gen"};
  21.                 AddBook(db, book2);
  22.                 //Linq查询
  23.                 var query = from b in db.Books
  24.                             orderby b.Title        //排序
  25.                             select b;
  26.                 WriteLine("All books in the database:");
  27.                 //foreach循环输出
  28.                 foreach (var b in query)
  29.                 {
  30.                     WriteLine($"{b.Title} by {b.Author}, code={b.Code}");
  31.                 }
  32.             }
  33.         }
  34.         //添加到数据库的方法
  35.         private static void AddBook(BookContext db, Book book)
  36.         {
  37.             var testQuery = from b in db.Books
  38.                             where b.Title == book.Title && b.Author == book.Author
  39.                             select b;
  40.             if (testQuery.Count() < 1)
  41.             {
  42.                 db.Books.Add(book);   //添加
  43.                 db.SaveChanges();     //保存
  44.             }
  45.         }
  46.     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值