我们的数据库没有设置正确的外键。我们现在使用该数据库生成 edmx。我们想要的是设置导航属性,以便我们可以从其他表中获取相应的详细信息。这是我们正在寻找的示例。
假设有一张员工和部门表。现在在数据库中,这些表之间没有关系,但 Employee 有从 Department 表中获取的 DepartmentId。
当我们获取 Employee 时,我们仅获得 DepartmentID,但我们还希望将 Department 作为属性一起获取,以便我们可以获得存储在 Department 表中的“DepartMentName”、“Location”等信息。
我们尝试在 EDMX 文件中添加导航属性,但它失败并不断给出与关系相关的错误。
请帮忙
你可以选择这样的东西。为员工和部门创建一个包装类。
public class EmpDept
{
public Employee Employee { get; set; }
public Department Department { get; set; }
}
public IEnumerable<EmpDept> GetEmployeesWithDeptpartment()
{
var result = from e in context.Employee
where e.Id == somevalue
select new EmpDept()
{
Employee = e,
Department = context.Department.Where(d => d.Id == e.DepartmentId)
};
return result.ToList();
}
这意味着您有一个额外的类,但它的编码快速且简单,易于扩展,可重用且类型安全。
希望这有帮助