I'm trying to save an entity, but this entity is related to another one and of this one I only have the id. For example, giving this structure:
public class Library
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public int LibraryId { get; set; }
public string Title { get; set; }
public Bookshelf Bookshelf { get; set; }
}
public class Bookshelf
{
public int Id { get; set; }
public string Color { get; set; }
}
I receive from the client a new book to save to the db. This book only contains the Title, the LibraryId and the BookshelfId (it's a DTO).
Now I want to save this book, creating the relationship with Library and Bookshelf, without retrieving the full object Library and Bookshelf, how can I do it easily?
What if, for example, I want to create a new library, and relate it to some already existing books? What I should do to achieve it?
I want to save this book, creating the relationship with Library and Bookshelf, without retrieving the full object Library and Bookshelf
Simply add a property BookshelfId on your book class.
public class Book
{
public int Id { get; set; }
public int LibraryId { get; set; }
public string Title { get; set; }
public Bookshelf Bookshelf { get; set; }
public int BookshelfId { get; set; }
}
Then you can do:
DbContext.Add(new Book { LibraryId = 1, BookshelfId = 1});
DbContext.SaveChanges();
What if, for example, I want to create a new library, and relate it to some already existing books
Add Library navigation property on the book
public class Book
{
public int Id { get; set; }
public Library Library { get; set; }
...
}
and then you can update the library property on the books using only their ids
var library = new Library { Name = "My library" };
DbContext.Libraries.Add(library);
var bookIds = new int[] {1, 2};
foreach(var bookId in bookIds) {
var book = new Book { Id= bookId, Library = library};
DbContext.Attach(book);
DbContext.Entry(book).Property(b => b.LibraryId).IsModified = true;
}
DbContext.SaveChanges();
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