c# - EFCore 保存具有关系 ID 的实体

标签 c# entity-framework asp.net-core entity-framework-core

我正在尝试保存一个实体,但该实体与另一个实体相关,并且我只有该实体的 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; }
}

我从客户端收到一本新书,要保存到数据库中。这本书只包含 TitleLibraryIdBookshelfId(它是一个 DTO)。 现在我想保存这本书,创建与 Library 和 Bookshelf 的关系,而不检索完整的对象 LibraryBookshelf,我怎样才能轻松做到这一点?

例如,如果我想创建一个新图书馆,并将其与一些现有的书籍相关联,该怎么办?我应该做什么来实现它?

最佳答案

我想保存这本书,创建与 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/

相关文章:

c# - 在 WPF-Desktop 程序中设置每像素位数

c# - 使用Entity Framework查询多表联合结果

entity-framework - Entity Framework 4.3.1 到 5.0 RC - 模型创建期间出现 NullReferenceException

c# - ASP.NET Core 2.0 升级 - 损坏的 NETStandard 库引用

c# - 构建 : error MSB4062 Microsoft. Build.Tasks.ResolveComReference 时出现 .NET Core 错误

.NET Core 指定的框架 'Microsoft.NETCore.App' ,版本 '1.1.2' 未找到

c# - MVVM中的ViewModelLocator是否为每个ViewModel在内存中保存实例?

c# - Documentum DFS,重命名 dm_user(user_name 属性)

c# - C# 中的 Exception 或 Either monad

c# - 是否应在 Web 应用程序中禁用 Entity Framework 延迟加载?