我的目标是在一个表/网格中显示HTML页面中两个表的数据。
ID,Forename,Surname,Hobby Name
表格
People(ID, Forename, Surname, Hobby ID)
Hobby(ID, Hobby Name)
namespace DC.ViewModels
{
public class PeopleHobbyView()
{
public int ID {get; set;}
public string Forename {get; set;}
public string Surname {get; set;}
public string Hobby_Name {get; set;}
}
public class PeopleHobbiesVM
{
public List<PeopleHobbyView> PeopleList { get; set; }
public void GetPeople()
{
using (var context = new LSF1617Entities())
{
var people = (from people in context.People join hobbies in context.Hobby on people.Hobby_ID equals hobbies.ID
select new PeopleHobbyView { ID = people.ID, Forename = people.Forename, Surname = people.Surname, Hobby_Name = hobbies.Hobby_Name}
);
this.PeopleList = people.ToList();
}
}
}
}
业余爱好名称当然必须在Hobby表中查找,所以我在GetPeople()
方法中创建了一个联接
这一切看起来有点长,我只是想确保这是一个很好的方式来完成任务。我已经阅读了一些关于懒惰/急切加载的内容,而且我似乎无法完全了解它。
答案 0 :(得分:1)
这是使用EF查询数据的完美方式。如果您愿意,可以使用navigation properties
它会删除此行
join hobbies in context.Hobby on people.Hobby_ID equals hobbies.ID
因为它将在导航属性中声明。
至于延迟加载,你真的不会在这种情况下使用它。如果结果非常长,您可能希望将结果分页。
我会将此代码移出视图模型并转移到控制器操作中。你通常会将你的上下文传递给控制器的构造函数。
public class SomeController : Controller {
public SomeController(LSF1617Entities dbContext)
{
_dbContext = dbContext;
}
public ActionResult Index()
{
var model = (from people in context.People join hobbies in context.Hobby on people.Hobby_ID equals hobbies.ID
select new PeopleHobbyView { ID = people.ID, Forename = people.Forename, Surname = people.Surname, Hobby_Name = hobbies.Hobby_Name}
).ToList();
return View(model);
}
答案 1 :(得分:1)
你几乎是正确的。
然而,我不会这样做,而是创建两个单独的模型。 一个用于'人',一个用于'爱好'。 这使得阅读更容易。
public class People
{
public int Id { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public Hobby Hobby { get; set; }
}
public class Hobby
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<People> People { get; set; }
}
在您的上下文中,您可以加载关系。如果你想要延迟加载,这个方法有点依赖。请阅读这篇文章:
https://msdn.microsoft.com/en-us/data/jj574232.aspx
只要您的数据库中存在关系并且设置了加载,每当您访问People对象时,它也会向您显示相关的爱好。
答案 2 :(得分:0)
试试这个
PeopleList = context.People.Include(x => x.Hobby).select(x => new PeopleHobbyView {
D = x.ID,
Forename = x.Forename,
Surname = x.Surname,
Hobby_Name = x.Hobby.Hobby_Name
}).toList();
没有太大区别,但你的方式完全没问题,唯一不同的是查询结束时的toList并且没有var人员分配到PeopleList