c# - Entity Framework 和连接表达式中的一对多配置

标签 c# entity-framework

我正在使用 EF codefirst。我对实体中的关系感到困惑。我有两个实体 StudentStandard。如下图

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int StdandardId { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    public string Description { get; set; }
}

他们是一对多的关系。 我可以通过像这样的简单连接表达式来做到这一点

var list = StudentList.Join
          (StandardList,c => c.StdandardId,o => o.StandardId,(c, o) => new
          {
              StudentId = c.StudentId,
              StudentName = c.StudentName,
              StandardName = o.StandardName
          });

那我为什么要配置forienkey一对多关系

public class Student
{
    public Student() { }
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int StdandardId { get; set; }    
    public virtual Standard Standard { get; set; }
}

public class Standard
{
    public Standard()
    {
        Students = new List<Student>();
    }

    public int StandardId { get; set; }
    public string StandardName { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

有什么关键的好处吗?哪一个会表现出色?

最佳答案

导航属性 (Students) 是一个隐式连接。但它是一个外连接。如果您显式加入,则可以强制执行内部联接,这通常会表现得更好。因此,如果性能至关重要,请执行此操作。

因此,请给自己机会同时做这两件事。创建导航属性并在必要时显式加入。

导航属性的好处是语法更加简洁。例如

from standard in Standards
select new { standard.StandardName , NrOfStudents = standard.Students.Count() })

对于此查询,您始终需要外部联接,因为您还希望报告学生为零的标准。

或者一个隐式的SelectMany:

from standard in Standards
where standard.StandardId == id
from student in standard.Students
select new { student. ... }

导航属性可帮助您在没有这种冗长的连接语法的情况下执行连接。

关于c# - Entity Framework 和连接表达式中的一对多配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038665/

相关文章:

c# - Linq-to-Entities 动态排序

c# - Linq Find 方法作为 IQueryable

c# - '无法从程序集加载类型 'Microsoft.AspNetCore.Mvc.MvcJsonOptions' 'Microsoft.AspNetCore.Mvc.Formatters.Json,版本=3.0.0.0

c# - REQ/REP 模式中的 ZeroMQ FiniteStateMachineException

c# - Dll 由未知公司签名?

sql - 为什么我的 Entity Framework 查询 Single 速度很慢?

vb.net - Entity Framework 异常 : Index was outside of the bounds of the array. "

c# - RabbitMQ:erl.exe 占用高 CPU 使用率

javascript - 将 Javascript 导航控件与 Blazor 结合使用

c# - 将 DbContext.SaveChanges 异常记录到 Entity Framework/Entity Framework Core 中的数据库