pelotu2
pelotu2

Reputation: 45

Entity Framework Core: Loop reference on getting rows

I have these 2 tables:

public class Book
{
    public Guid Id { get; set; }
    public Library Library { get; set; }
}

public class Library
{
    public Guid Id { get; set; }
    public ICollection<Book> Books { get; set; }
}

Well, when I run this code:

_context.Books.Include(b => b.Library).ToList();

I want to get only the books with their library and the entity Library with the Books property as null. But I get this property with every books of the libraries, then when I want to update one book always throw the Exception:

The instance of entity type 'Book' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.

Is there any way to get all the books with the Library property Books as null value?

Upvotes: 3

Views: 1105

Answers (1)

atiyar
atiyar

Reputation: 8305

Is there any way to get all the books with the Library property Books as null value?

If that is your only requirement, then use projection like -

var books = _context.Books
        .Select(p => new Book
        {
            Id = p.Id,
            Library = new Library { Id = p.Library.Id }
        }).ToList();

If you have lots of properties in your models, you might want to consider using AutoMapper to do the projection for you, like -

var books = Mapper.ProjectTo<BookDTO>(_context.Books).ToList();

You will need to define DTO models with only the properties you need, like -

public class BookDTO
{
    public int Id { get; set; }
    public LibraryDTO Library { get; set; }
}

public class LibraryDTO
{
    public int Id { get; set; }
}

and to define the mappings for them -

CreateMap<Book, BookDTO>();
CreateMap<Library, LibraryDTO>();

Upvotes: 1

Related Questions