在不加入 Entity-to-Linq 的情况下获取外键值

Get foreign key value without join In Entity-to-Linq

Employee table 具有与 Department table 的 Id 列相关的 Departmentid 外键。

现在,如果我 select 来自 Employee table 的所有行,我应该在 [= 的外键列中获取它们各自 DepartmentId 的部门名称12=] table.

我正在使用 Entity Framework 我可以通过创建 Department table.

的另一个对象来使用 join 来做事

输出应该是这样的:

EmployeeName    EmployeeAddress  EmployeeDepartment
    abc            xyz                  IT

它应该自动获取 Employee

的外键值
lamiEntities1 lam = new lamiEntities1();
        var query =( from sls in lam.sales.AsEnumerable() join it in lam.items on sls.ItemId equals it.Id orderby sls.Id descending
                    select new

                    {
                        ItemName = it.ItemName,
                        TotalAmounts = sls.Amount,
                        Remarks=sls.Remarks,
                        Dates = sls.Date

                    }).Take(20);

        GridView1.DataSource = query;
        GridView1.DataBind();

这里我如何删除连接并使用 itemid 外键直接使用 itemname

我想这就是您要找的东西:

你可以做一个DTO(Data Transfer Object),在层之间传输数据

public class EmployeeWithDepartmentDto
{
    public string EmployeeName { get; set; }
    public string EmployeeAddress { get; set; }
    public string DepartmentName { get; set; }
}

你会得到这样的结果:

var result = employeeRepository.Select(e => new EmployeeWithDepartmentDto { EmployeeName = e.Name, EmployeeAddress = e.Address, DepartmentName = e.Department.Name });

foreach (var employeeWithDepartmentDto in result)
     Console.WriteLine($"Name: {employeeWithDepartmentDto.EmployeeName}, Address: {employeeWithDepartmentDto.EmployeeAddress}, Department: {employeeWithDepartmentDto.DepartmentName}");

Here is an example in DotNetFiddle

如果您不想创建 DTO class,您可以使用匿名对象进行查询

var result = employeeRepository.Select(e => new { EmployeeName = e.Name, EmployeeAddress = e.Address, DepartmentName = e.Department.Name });

或者您可以这样查询,使用 Linq-To-Sql:

var result = from e in employeeRepository
                select new EmployeeWithDepartmentDto
                {
                    EmployeeName = e.Name,
                    EmployeeAddress = e.Address,
                    DepartmentName = e.Department.Name
                }

如果将 EF 与 Eager Loading 一起使用,则必须使用 Include,这样:

lamiEntities1 lam = new lamiEntities1();
    var query =( from sls in lam.sales.Include("item")
                orderby sls.Id descending
                select new

                {
                    ItemName = sls.Item.ItemName,
                    TotalAmounts = sls.Amount,
                    Remarks=sls.Remarks,
                    Dates = sls.Date

                }).Take(20);