Code First 通过代码反向生成数据库,无需关心数据库方面
1 新建一个控制台项目
2 打开NuGet程序包管理,添加EntityFramework
添加完成后查看是否有如下两个引用
3 代码编写及配置
新建Goods类
1 class Goods 2 { 3 [Key] 4 public int GID { get; set; } 5 public string GName { get; set; } 6 public int GPrice { get; set; } 7 public int Shelf_SID { get; set; } 8 }
新建Shelves
1 class Shelves 2 { 3 [Key] 4 public int SID { get; set; } 5 public string SPosition { get; set; } 6 public string SName { get; set; } 7 }
新建上下文SaleContext
1 class SaleContext: DbContext 2 { 3 public SaleContext(): base("name=SaleMarket") 4 { 5 } 6 7 public virtual DbSet<Goods> Goods { get; set; } 8 public virtual DbSet<Shelves> Shelf { get; set; } 9 }
App.config中添加数据库连接
1 <connectionStrings> 2 <add name="SaleMarket" connectionString="data source=IP;initial catalog=SaleMarket;User Id=sa;Password=******" providerName="System.Data.SqlClient"/> 3 </connectionStrings>
4 数据库创建及实例操作
1 using (var smContext=new SaleContext()) 2 { 3 if (smContext.Database.CreateIfNotExists()) 4 { 5 Console.WriteLine("创建成功"); 6 } 7 else 8 { 9 Console.WriteLine("数据库已存在"); 10 } 11 //CRUD 12 List<Shelves> s1 = new List<Shelves> 13 { 14 new Shelves 15 { 16 SID=1, 17 SName="糖果区", 18 SPosition="1L-09N", 19 20 }, 21 new Shelves 22 { 23 SID=2, 24 SName="瓜子区", 25 SPosition="1L-08N", 26 27 } 28 }; 29 List<Goods> g1 = new List<Goods> 30 { 31 new Goods 32 { 33 GID=1, 34 GName="大白兔", 35 GPrice=16, 36 Shelf_SID=1 37 }, 38 new Goods 39 { 40 GID=2, 41 GName="巧克力", 42 GPrice=32, 43 Shelf_SID=1 44 }, 45 new Goods 46 { 47 GID=3, 48 GName="焦糖味", 49 GPrice=15, 50 Shelf_SID=2 51 }, 52 new Goods 53 { 54 GID=4, 55 GName="原味", 56 GPrice=12, 57 Shelf_SID=2 58 }, 59 new Goods 60 { 61 GID=5, 62 GName="五香味", 63 GPrice=10, 64 Shelf_SID=2 65 } 66 }; 67 smContext.Shelf.AddRange(s1); 68 smContext.Goods.AddRange(g1); 69 smContext.SaveChanges(); 70 var p = smContext.Goods.Join(smContext.Shelf, g => g.Shelf_SID, s => s.SID, (g, s) => new { g.GName,g.GPrice,s.SName,s.SPosition }).Where(gs=>gs.GPrice>16); 71 foreach (var item in p) 72 { 73 Console.WriteLine($"{ item.GName}在{item.SPosition}的{item.SName},价格是{item.GPrice}"); 74 } 75 } 76 Console.ReadKey();
打开数据库查看,数据库已创建
结果显示