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?
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With