Employee
表包含Departmentid
个外键,与Department
表的Id
列有关。
现在,如果我从Employee
表中选择所有行,我应该在DepartmentId
表的外键列中获取各自Employee
的部门名称。
我正在使用实体框架我可以通过创建Department
表的另一个对象来使用连接做事。
输出应该是:
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 forign key
直接使用itemname答案 0 :(得分:1)
我想这就是你要找的东西:
您可以制作DTO(数据传输对象),在层之间传输数据
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类,可以使用匿名对象进行查询
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);