Code First 通过代码反向生成数据库,无需关心数据库方面
1 新建一个控制台项目
2 打开NuGet程序包管理,添加EntityFramework
添加完成后查看是否有如下两个引用
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();
打开数据库查看,数据库已创建
结果显示