1.基础CRUD

在ef中,CUD都使用Datacontext.SaveChange()进行保存.

SavaChange方法在保存之前会自动调用DetectChanges方法检查DataContext中做了什么更改,以作出对应的数据库操作.

 

create 增

dbcontext.dbset.add(model),然后再调用datacontext.savechanged();

using (var context = new BookStore())
{
    Author author = new Author()
    {
        FirstName = "Mark",
        LastName = "Johny",
    };
    
    context.Authors.Add(author);
    context.SaveChanges();
}

update 改

using (var context = new BookStore())
{
    var author = context.Authors
        .FirstOrDefault();

    author.LastName = "Cuban";
    context.SaveChanges();
}

 

delete 删

datacontext.dbset.remove(model); 再datacontext.savechangs();

如果model不在数据库中则从datacontext中删除,否则数据库和datacontext都会删除.

using (var context = new BookStore())
{
    var author = context.Authors
        .Where(a => a.AuthorId == 2)
        .FirstOrDefault();
            
        context.Authors.Remove(author);
        context.SaveChanges();
}

 

posted @ 2019-09-09 21:33  马肯尼煤牙巴骨  阅读(202)  评论(0编辑  收藏  举报