Code First 通過代碼反向生成資料庫,無需關心資料庫方面
1 建立一個控制台項目
2 打開NuGet程式包管理,添加EntityFramework
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNCM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TUtVWds1GZ5ZkMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLyUzN1AjN1QTMzIjMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
添加完成後檢視是否有如下兩個引用
3 代碼編寫及配置
建立Goods類
class Goods
{
[Key]
public int GID { get; set; }
public string GName { get; set; }
public int GPrice { get; set; }
public int Shelf_SID { get; set; }
}
建立Shelves類
class Shelves
{
[Key]
public int SID { get; set; }
public string SPosition { get; set; }
public string SName { get; set; }
}
建立上下文SaleContext
class SaleContext:DbContext
{
public SaleContext():base("name=SaleMarket")
{
}
public virtual DbSet<Goods> Goods { get; set; }
public virtual DbSet<Shelves> Shelf { get; set; }
}
App.config中添加資料庫連接配接
<connectionStrings>
<add name="SaleMarket" connectionString="data source=IP;initial Catalog=SaleMarket;user id=sa;password=*****;" providerName="System.Data.SqlClient"/>
</connectionStrings>
4 資料庫建立及執行個體操作
using(var smContext=new SaleContext())
{
if (smContext.Database.CreateIfNotExists())
{
Console.WriteLine("建立成功");
}
else
{
Console.WriteLine("資料庫已存在");
}
//CRUD
List<Shelves> s1 = new List<Shelves>
{
new Shelves
{
SID=1,
SName="糖果區",
SPosition="1L-09N",
},
new Shelves
{
SID=2,
SName="瓜子區",
SPosition="1L-08N",
}
};
List<Goods> g1 = new List<Goods>
{
new Goods
{
GID=1,
GName="大白兔",
GPrice=16
Shelf_SID=1
},
new Goods
{
GID=2,
GName="巧克力",
GPrice=32,
Shelf_SID=1
},
new Goods
{
GID=3,
GName="焦糖味",
GPrice=15,
Shelf_SID=2
},
new Goods
{
GID=4,
GName="原味",
GPrice=12,
Shelf_SID=2
},
new Goods
{
GID=5,
GName="五香味",
GPrice=10,
Shelf_SID=2
},
};
smContext.Shelf.AddRange(s1);
smContext.Goods.AddRange(g1);
smContex.SaveChanges();
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);
foreach (var item in p)
{
Console.WriteLine($"{item.GName}在{item.SPosition}的{item.SName},價格是{item.GPrice}");
}
}
Console.ReadKey();
打開資料庫檢視,資料庫已建立
結果顯示