简体   繁体   English

使用 Code First 和 EF.Core 引用表以进行有效搜索的正确方法是什么

[英]What's the correct way to reference tables using Code First with EF.Core for searching efficiently

Fairly new to EF.Core and I'm having some issues as my tables start getting more complex. EF.Core 相当新,随着我的表开始变得越来越复杂,我遇到了一些问题。 Here's an example of what I have defined for my classes.这是我为我的类定义的示例。 Note... there are many more columns and tables than what I have defined below.注意...列和表比我在下面定义的要多得多。 I've paired them down for brevity.为了简洁起见,我将它们配对。

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool Active { get; set; }
}

Followed by其次是

public class JournalEntry
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Details { get; set; }
    public DateTime DateEntered { get; set; }
    public virtual User User { get; set; }
}

I want to be able to issue the following query and INCLUDE the User Table so that I can then populate a ViewModel with columns from the User Table without having to do another lookup and also to sort the data while retrieving it:我希望能够发出以下查询并包含用户表,以便我可以使用用户表中的列填充 ViewModel,而无需进行另一次查找,并且在检索数据时对数据进行排序:

public IQueryable<JournalEntry> GetByUser(int userId)
{
    return _DbContext.JournalEntries.Where(j => j.UserId == userId)
                                            .Include(u => u.User)
                                            .OrderBy(u=> u.User.FirstName)
                                                .ThenBy(j => j.DateEntered);
}

My controller would then have something similar to the following:然后,我的 controller 将具有类似于以下内容的内容:

public IActionResult List(int userId)
{
    var journalEntries = new _dbRepository.GetByUser(userId);
    var myViewModel = new MyViewModel();
    myViewModel.UserName = ($"{journalEntries.User.FirstName} {journalEntries.User.LastName}");
    myViewModel.Entries = journalEntries; 
    etc ....
    return View(myViewModel);
}

I'm loading the user's first and last name in the View Model and whatever other attributes from the various tables that are referenced.我在视图 Model 中加载用户的名字和姓氏,以及引用的各种表中的任何其他属性。 The problem that I'm having is that I'm getting errors on the Migration creation " Foreign key constraint may cause cycle or multiple cascade paths. " And of course, if I remove the line reading public virtual User User { get;我遇到的问题是我在迁移创建时遇到错误“外键约束可能导致循环或多个级联路径。 ”当然,如果我删除读取公共虚拟用户用户 {get; set;放; } from the JournalEntry class then the problem goes away (as one would expect).JournalEntry class然后问题就消失了(正如人们所期望的那样)。

I believe that the way I'm doing the models is incorrect.我相信我做模型的方式是不正确的。 What would be the recommended way that I should code these models?我应该对这些模型进行编码的推荐方式是什么? I've heard of "lazy loading".我听说过“延迟加载”。 Is that what I should be moving towards?那是我应该走向的方向吗?

Thanks a bunch.谢谢一堆。

--- Val --- 值

Your query returns an IQueryable<JournalEntry> not a JournalEntry .您的查询返回IQueryable<JournalEntry>而不是JournalEntry Change the code to get the user details from the first object:更改代码以从第一个 object 获取用户详细信息:

var myViewModel.UserName = ($"{journalEntries.First().User.FirstName} {journalEntries.First().User.LastName}");

In the line above I'm calling First() on your journal entries collection and that would have a User .在上面的行中,我在您的日记条目集合上调用First() ,这将有一个User Then I can access FirstName and LastName .然后我可以访问FirstNameLastName

Also, don't bother with LazyLoading since you are learning.另外,因为您正在学习,所以不要打扰LazyLoading It could cause select n+1 issues if used incorrectly如果使用不当,可能会导致select n+1问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 EF.Core Database First 包含特殊字符 $ 脚手架表 - How do I Scaffold tables with EF.Core Database First containing special characters $ .NET Core 3 / EF.Core 3:`QueryModelGenerator`、`RelationalQueryModelVisitor` 等发生了什么 - .NET Core 3 / EF.Core 3: what happened to `QueryModelGenerator`, `RelationalQueryModelVisitor` and etc 在EF Core中加载对象引用集合的正确方法是什么? - What is the correct way to load a collection of a reference of an object in EF Core? 如何在 EF.core 中使用 FromSqlRaw 指定列 - How can I specific columns using FromSqlRaw in EF.core 首先使用 EF Core 代码在两个表之间进行映射 - mapping between two tables using EF Core Code first 如何在LINQ或EF.Core中执行此操作? - How to do this in LINQ or EF.Core? 使用 .ToLookup() 和 EF Core 查询的正确方法 - Correct way of using .ToLookup() with an EF Core query 首先在EF核心代码中建立一元关系的正确方法是什么? - What is the proper way to have unary relationship in EF-core code first? 如何启用 append 仅具有 EF 核心 6 代码的分类帐表 - How to enable append only ledger tables with EF core 6 code first .NET Core / EF.Core 3+ 将控制台日志记录添加到 DbContext - .NET Core / EF.Core 3+ add Console logging to DbContext
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM