EF 检查集合初始化状态

本文关键字:状态 初始化 集合 检查 EF | 更新日期: 2023-09-27 18:28:06

让我们假设以下类:

public class Author
{
    public virtual string Name { get; set; }
    public virtual List<Book> Books { get; set; }
} 
public class Book
{
    public virtual string Name { get; set; }
    public virtual Author Author { get; set; }
}
public class Controller
{
    public void DeleteBook(Book book)
    {
        var author = book.Author; //first check if it is loaded, not to invoke lazy loading?
        author.Books.Remove(book) //check if the books collection is loaded?
        book.Author = null;
        Context.Set<Book>().Remove(book);        
    }
}

我的问题是 - EF 中有没有办法检查两个"已加载"状态?我想确保书籍作者和书籍收藏不会只是为了解除关联而加载。

我想写这样的东西:

public class Controller
{
    public void DeleteBook(Book book)
    {
        if (EF.IsLoaded(book.Author)) //has it been (lazy) loaded / initialized?
        {
             if (EF.IsLoaded(book.Author.Books) //has it been (lazy) loaded / initialized?
             {
                 book.Author.Books.Remove(book);
             }
             book.Author = null;
        }
        Context.Set<Book>().Remove(book);        
    }
}

这可能吗?

EF 检查集合初始化状态

我知道您可以使用RelationshipManager来检查集合是否加载,该将适用于任何包含关系的实体,并实现IEntityWithRelationships

 var result = ((IEntityWithRelationships)(author)).RelationshipManager
       .GetRelatedCollection<Books>("FK_Authors_Books", "Books");
   if (result.IsLoaded == false)
   {
       // do something here
   }

注意:您必须替换正确的外键名称而不是"FK_Authors_Books"。

我相信您也可以对单个对象使用GetRelatedReference做同样的事情。

 var result = ((IEntityWithRelationships)(book)).RelationshipManager
       .GetRelatedReference<Author>("FK_Books_Author", "Author");
   if (result.IsLoaded == false)
   {
       // do something here
   }

在DBContext中,您可以检查它加载的对象是否访问属性Local,例如:DBContext.Book.Local

我想你可以做这样的事情

public IsLoaded(Book book)
{
    DBContext.Book.Local.Count(b => b.ID == book.ID) > 0;
}

请记住,我不是 EF 专家,但也许它会给你一个想法。DbContext.Entry 方法使您可以访问 DBContext 包含的有关实体的所有信息。在我的理解中,您想知道传递的对象(作为参数(是否已经在内存中?

另请记住,以下方法是使用显式加载。

public class Controller
{
    public void DeleteBook(Book book)
    {
        // assuming that you're working on context directly and need to dispose it
        using (var context = new YourContext())
        {
            var entry = context.Entry(book);
            // Will tell you if Author navigation property is loaded
            bool isLoaded = entry.Reference(x => x.Author).IsLoaded();
            if (isLoaded != false)
            {
                // do when Author navigation property is loaded
            }
            else
            {
                // do when Author navigation property is not loaded
            }
        }
     }
}

对于类型为"集合"的导航属性,您只需使用 .集合而不是 。参考。

http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.relatedend.isloaded(v=vs.110(.aspx