0

嗨,我在我的项目中使用剑道 ui 网格。

这是我在数据库中插入记录的代码。

 public static void Insert(StudentViewModel student)
        {
            student.StudentId = All().OrderByDescending(p => p.StudentId).First().StudentId + 1;

            //All().Insert(0, student);
             UniRegEntities uniRegEntities = new UniRegEntities();
            Student stu =new Student();
            stu.FName = student.FirstName;
            stu.LName = student.LastName;
            stu.Gender = uniRegEntities.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
            stu.Id = student.StudentId;

            uniRegEntities.Students.Add(stu);
            uniRegEntities.SaveChanges();
        }

这是我的更新声明。

 public static void Update(StudentViewModel student)
        {
          UniRegEntities context = new UniRegEntities();
            var studentToUpdate = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
            studentToUpdate.FName = student.FirstName;
            studentToUpdate.LName = student.LastName;
            studentToUpdate.Gender = context.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
            context.SaveChanges();

        }

任何人都可以建议我删除方法?

4

3 回答 3

0

你能试试下面的代码片段吗?

using (var db= new AppContext(ConnectionStr))
{
        try
        {
            con.Configuration.AutoDetectChangesEnabled = false;
            var o = new Student { StudentId = student.StudentId };
            db.Students.Attach(o);
            db.Students.Remove(o);
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.InnerException.Message);
        }
        finally
        {
            con.Configuration.AutoDetectChangesEnabled = true;
        }
}
于 2013-06-21T13:30:53.263 回答
0

您可以从数据库中获取实体然后将其删除,也可以创建一个实体然后将其删除。

所以:

var e = // Get
ctx.DeleteObject(e);
ctx.SaveChanges();

或者

var e = new Foo() { FooId = id };
ctx.Entity.Attach(e);
ctx.DeleteObject(e);
ctx.SaveChanges();

适用于您的情况:

您正在获取记录,因此您想使用DeleteObject()

public static void Update(StudentViewModel student)
{
    UniRegEntities context = new UniRegEntities();

    var studentToDelete = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();

    context.Students.DeleteObject(studentToUpdate);
    context.SaveChanges();
}
于 2013-06-21T13:31:20.177 回答
0
context.Students.Remove(context.students.Single(x=>x.Id==student.Id));
于 2013-06-21T13:32:58.210 回答