我正在尝试保存一个实体,但该实体与另一个实体相关,并且我只有该实体的 ID。例如,给出以下结构:
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; }
}
我从客户端收到一本新书,要保存到数据库中。这本书只包含 Title
、LibraryId
和 BookshelfId
(它是一个 DTO)。
现在我想保存这本书,创建与 Library 和 Bookshelf 的关系,而不检索完整的对象 Library
和 Bookshelf
,我怎样才能轻松做到这一点?
例如,如果我想创建一个新图书馆,并将其与一些现有的书籍相关联,该怎么办?我应该做什么来实现它?
最佳答案
我想保存这本书,创建与 Library 和 Bookshelf 的关系,而不检索完整的对象 Library 和 Bookshelf
只需在您的图书类中添加属性 BookshelfId 即可。
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; }
}
然后你可以这样做:
DbContext.Add(new Book { LibraryId = 1, BookshelfId = 1});
DbContext.SaveChanges();
例如,如果我想创建一个新图书馆,并将其与一些现有的书籍关联起来,该怎么办
在书中添加图书馆导航属性
public class Book
{
public int Id { get; set; }
public Library Library { get; set; }
...
}
然后您可以仅使用书籍的 ID 来更新书籍的图书馆属性
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();
关于c# - EFCore 保存具有关系 ID 的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56504872/