EF增删改查操作
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Model1Container m = new Model1Container();
Student s = new Student();
s.Name = "小明";
m.Student集.AddObject(s); //增加操作
m.SaveChanges(); //运行增加
Console.WriteLine("增加成功");
var Slist = from Stu in m.Student集 select Stu; //查询操作
foreach (Student sl in Slist)
{
Console.WriteLine("输出的学生名字为:");
Console.WriteLine(sl.Name);
}
Console.WriteLine("更新操作");
Student sc = new Student();
sc.ID = 2;
sc.Name = "小改明";
m.Student集.Attach(sc); //这句很重要把要更新的实体写入实体集中
m.ObjectStateManager.ChangeObjectState(sc, System.Data.EntityState.Modified); //对实体进行更新
m.SaveChanges(); //运行更新操作
Console.WriteLine("删除操作");
Student sd = new Student();
sd.ID = 3;
m.Student集.Attach(sd);
m.ObjectStateManager.ChangeObjectState(sd, System.Data.EntityState.Deleted); //删除操作
m.SaveChanges();
}
}
}