实体框架 - 列表(MVC)

发布于 2025-02-02 03:33:33 字数 635 浏览 1 评论 0原文

public class Author
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    
    public ICollection<Book> Books { get; set; } = new List<Book>();
};

public class Book
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public int AuthorId { get; set; }
    public Author? author { get; set; }
};

我的代码与此类似,我可以在作者控制器列表中分配给作者。书籍还是仅用于关系的属性?

例如,

author.Books = await _context.Books.Where(b => b.AuthorId == Id).ToListAsync();

它是正确的代码还是创建未图表的属性?

public class Author
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    
    public ICollection<Book> Books { get; set; } = new List<Book>();
};

public class Book
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public int AuthorId { get; set; }
    public Author? author { get; set; }
};

I have code similar to this, can I assign in author controller list of books to author.Books or it's property only for relation?

For example

author.Books = await _context.Books.Where(b => b.AuthorId == Id).ToListAsync();

It's correct code or create NotMapped property?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔嚣张 2025-02-09 03:33:33

您可以获取带有作者查询的书籍,并且无需

使用include()这样的书来获取新书以获取书籍:

 var author=await _context.Author.Include(a=>a.books).ToListAsync()

you can get books with author query and there is no need to make a new one to get books

by using Include() like this :

 var author=await _context.Author.Include(a=>a.books).ToListAsync()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文