Linq 返回外键引用的数据
我有一个简单的数据库,其中有两个表 employee
和 employeedetails
。
employee
具有指向表 employeedetails
的外键 empdetailsid
我返回雇员的简单 linq 查询
var employeeList = from employee in objectcontext.employees select employee;
return employeeList.ToList();
也返回了 employeedetails 及其包含的所有字段,但我没有返回需要。 我正在使用实体框架 4.0。有没有办法避免获取所有不必要的数据。 我可以定义一个只有员工表字段并可以加载到其中的模型类,但我想知道是否有更简单的方法。我使用的是mysql数据库。
I have a simple db with two tables employee
and employeedetails
.
employee
has foreignkey empdetailsid
that points to the table employeedetails
My simple linq query to return employee
var employeeList = from employee in objectcontext.employees select employee;
return employeeList.ToList();
also returns employeedetails and all its contained fields which I do not need.
I am using Entity Framework 4.0. Is there a way to avoid getting all the unnecessary data.
I could go with defining a model class that just has the employee table fields and could load into that but I was wondering if there was a simpler way. I am using a mysql database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您如何知道查询返回员工详细信息?您是否检查了生成的 SQL 查询,或者您是否只是尝试访问 EmployeeDetails 对象并获取数据。在第二种情况下,EF 确实可能只是按需延迟加载数据(当您尝试访问数据时)。否则,如果您确定在执行初始查询期间获取了额外的数据,请尝试在运行查询之前隐式启用延迟加载:
How do you know that the query returns employee details? Have you checked the generated SQL query, or did you just try to access the
EmployeeDetails
object and got the data. In the second case, EF could indeed just be lazy-loading the data on demand (when you try to access it). Otherwise, if you are sure the extra data gets fetched during the execution of the initial query, try implicitly enabling lazy loading before running the query:我没有使用过 ef 4,但大多数 orm 倾向于使用一个称为延迟加载的概念。仅当调用该对象时才会检索相关员工详细信息中的数据。当您在调试器中查看该对象时,单击该对象时将检索特定员工详细信息的数据。为了更好地了解正在检索哪些数据,您需要对数据库运行探查器以捕获正在进行的 SQL 查询。我不知道mysql是否有像sql server一样的内置分析器。如果没有检查nhprof。
I haven't used ef 4, but most orm's tend to use a concept called lazy loading. The data in the related employee details is only retrieved when a call is made to that object. when you look at the object in your debugger the data for a specific employee details will be retrieved when you click on the object. To get a better idea of what data is being retrieved you will need to run a profiler against the database to trap the sql queries being made. I don't know if mysql has a built in profiler like sql server. If not check out nhprof.