其他分享
首页 > 其他分享> > 6.实体与上下文的关系

6.实体与上下文的关系

作者:互联网

datacontext会自动跟踪实体状态,当我们调用savechanges保存实体到数据库时,会用到跟踪状态.

但是某些情况下,实体 不在datacontext中,他们没有连接关系,比如:一个datacontext查询,别一个datacontext保存,这种情况下保存的datacontext不知道查询出来的这些实体的状态.

 

添加新的新实体到datacontext有两种方法

using(var context = new BookStore())
{
    Author author = new Author()
    {
        //code here
    };
    
    context.Authors.Add(author);
    Console.WriteLine("Entity State: {0}", context.Entry(author).State);
    context.SaveChanges();
}

using(var context = new BookStore())
{
    Author author = new Author()
    {
        //code here
    };
    
    context.Entry(author).State = EntityState.Added;
    Console.WriteLine("Entity State: {0}", context.Entry(author).State);
    context.SaveChanges();
}

 

 

添加已存在的实体到datacontext也有两种写法

using(var context = new BookStore())
{
    context.Authors.Attach(existingAuthor);
    Console.WriteLine("Entity State: {0}", context.Entry(existingAuthor).State);
    context.SaveChanges();
}

using(var context = new BookStore())
{
    context.Entry(existingAuthor).State = EntityState.Unchanged;//这里也可以修改为modified ,看情况
    Console.WriteLine("Entity State: {0}", context.Entry(existingAuthor).State);
    context.SaveChanges();
}

 

 

ef检测是否存在数据库的方法

public void InsertOrUpdate(Author author)
{
    using (var context = new BookStore())
    {
        context.Entry(author).State = author.AuthorId == 0 ?
            EntityState.Added :
            EntityState.Modified;

        context.SaveChanges();
    }
}

 

标签:关系,datacontext,author,实体,State,context,new,Entry,上下文
来源: https://www.cnblogs.com/nocanstillbb/p/11494829.html