EF 簡單 增刪改查
阿新 • • 發佈:2021-07-14
一、新建Models 中實體類
在類中新增特性,新增特性之前需要引用名稱空間
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
1、類的上邊 [Table("表名稱")] 2、主鍵 [Key]
[Table("Student")]
public class Student
{
[Key]
public int SId { get; set; }
[Required(ErrorMessage ="請輸入姓名")]
[StringLength(50)]
public string SName { get; set; }
}
二、新建Dal資料夾
1、右鍵-》新建項-》左邊點資料,右邊點 ADO.NET 實體資料模型-》選擇空Code First 模型
2、在實體資料模型當中 新增 資料集屬性
public DbSet<Model實體類> 屬性名 { get; set; }--格式
public DbSet<Student> Students { get; set; }--例
三、更改web.config 資料庫連線字串
1、更改connectionString屬性名 data source 值 改成 .或資料庫例項名稱
2、更改connectionString屬性名 initial catalog 值 改成 自定義資料庫名稱
四、完成資料遷移命令-》選單點-》工具-》NuGet包管理器->程式包管理器控制檯
1、Enable-Migrations 啟動遷移(將自動生成的Configuration檔案中 AutomaticMigrationsEnabled =true)允許自動遷移
2、add-Migration init (init 名稱自定義)
3、update-database 完成更資料庫 遷移操作
五、增刪改查之前例項化上下文
//上下文
Model1 db = new Model1();
六、新增
例子:
public int Add(Student stu)
{
db.Students.Add(stu);//更改狀態為“新增”
return db.SaveChanges();//受影響行數
}
七、刪除
public int Del(int id)
{
//先通過id查詢
var item= db.Students.Find(id);
//刪除(更改狀態)
db.Students.Remove(item);
//操作資料庫
return db.SaveChanges();
}
八、顯示
public List<Student> show()
{
return db.Students.ToList();//將資料轉換為List集合
}
九、編輯
public Student FinById(int id)
{
return db.Students.Find(id);//按id查詢
}
十、修改
public int Edit(Student stu)
{
//將實體類的狀態改為“修改”狀態
db.Entry(stu).State = System.Data.Entity.EntityState.Modified;
//受影響行數
return db.SaveChanges();
}