Linq(ef)的增删查的语法

增加

//查询带有外键键的
  using (StudentDbEntities db = new StudentDbEntities())
            {
            //映射
                var avb = db.Student.Include("grade1").Select(s => new
                {
                    id = s.id,
                    name = s.name,
                    age = s.age,
                    //gradnaem 这个名字是随便起的
                   //grade1 是ef中虚拟的列  通过这个列可以关联到主表
                    gradnaem = s.grade1.gradename//外键   grade1.后面写你需要的类名就可以了



                }).ToList();
                dataGridView1.DataSource = avb;
            }

添加

  public static  bool  Add(Student student) {
            using (StudentDbEntities db=new StudentDbEntities())
            {
                db.Student.Add(student);
                return db.SaveChanges() > 0;
            }
        }

删除

 public static bool delete(int id) {
            using (StudentDbEntities db=new StudentDbEntities())
            {
                var sc = db.Student.FirstOrDefault(s => s.id == id);
                db.Student.Remove(sc);
             return  db.SaveChanges()>0;

            }
        
        } 

你可能感兴趣的:(ASP.NET)