我有3个表/实体,分别称为Person,PersonPhone和EmailAddress。所有表ID使用称为BusinessEntityID的相同ID。 “ BusinessEntity”也是一个表。我创建了一个ViewModel传递给我的View,它将显示一些数据:@model CoreTutorials1.ViewModels.PersonIndexViewModel<html xmlns="http://www.w3.org/1999/xhtml"><head> <title>@Model.Person.FirstName @Model.Person.LastName</title></head><body> <dl> <dt><b>First Name: </b></dt> <dd>@Model.Person.FirstName</dd> </dl> <dl> <dt><b>Last Name: </b></dt> <dd>@Model.Person.LastName</dd> </dl> <dl> <dt><b>Phone: </b></dt> <dd>@Model.PersonPhone.PhoneNumber</dd> </dl> <dl> <dt><b>Email Address: </b></dt> <dd>@Model.EmailAddress.EmailAddress1</dd> </dl></body></html>在我的控制器中,我已经尝试执行以下操作(排序):// GET: /<controller>/ public IActionResult Index() { // will grab the first Person from our DbSet from our db //var person = db.Person.FirstOrDefault(); var person = db.Person.Where(x => x.BusinessEntityId == 1).FirstOrDefault(); var a = from ea in db.EmailAddress join p in db.Person on ea.BusinessEntityId equals p.BusinessEntityId join pp in db.PersonPhone on p.BusinessEntityId equals pp.BusinessEntityId where p.BusinessEntityId == person.BusinessEntityId select new { }; PersonIndexViewModel vm = new PersonIndexViewModel() { Person = person, PersonPhone = person.PersonPhone.FirstOrDefault(), EmailAddress = person.EmailAddress.FirstOrDefault() }; // pass the viewmodel so it's data can be accessed in the view (Person, PersonPhone, EmailAddress) return View(vm); }我的主要目标是可以将PhoneNumber和EmailAddress附加到Person对象,以便在分配如下值后可以在ViewModel中使用它:PersonPhone = person.PersonPhone.FirstOrDefault(),EmailAddress = person.EmailAddress.FirstOrDefault()然后在我的ViewModel中,例如@Model.PersonPhone.PhoneNumber 最佳答案 public IActionResult Index(){ var vm = from p in db.Person where p.BusinessEntityId == 1 select new PersonIndexViewModel { Person = p, PersonPhone = p.PersonPhone.FirstOrDefault(), EmailAddress = p.EmailAddress.FirstOrDefault() }; return View(vm.FirstOrDefault());}如果要每人显示多个语音/邮件,则需要将PersonIndexViewModel.PersonPhone和PersonIndexViewModel.EmailAddress类型更改为List ,并用ToList()代替FirstOrDefault()填充,并在剃刀视图中编写foreach语句。关于c# - 如何使用LINQ SQL连接基于ID连接3个表? C#MVC(.NET Core 2.0),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47094782/ 10-12 16:22