我所做的工作有效,但这是错误的,我知道。
public Profile GetProfile(int id)
{
Profile profile = (
from u in en.User where u.UserID == id
select u.Profile.FirstOrDefault()
).First();
if (profile.UserReference.Value == null)
profile.UserReference.Load();
return profile;
}
Profile.UserID 是绑定(bind)到 User.UserID 的 FK。因此, Entity Framework 不将 Profile.UserID 包含在实体模型中,这就是为什么我的 linq 查询首先查找 User 对象,然后选择相关的 Profile 对象(这对我来说感觉很脏)。
谁能提供更好的解决方案:
- 通过 User.UserID 查找 Profile 对象。
- 在返回的 Profile 对象中加载 User 对象引用。
提前致谢!
最佳答案
尝试使用 Include方法
public Profile GetProfile(int id)
{
return (from p in db.Profiles.Include("User")
where p.User.UserId == id
select p).FirstOrDefault();
}
此方法返回配置文件对象,其中已加载用户引用。
关于c# - 如何使用 ADO.net Entity Framework 正确加载对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/690666/