我有搜索在两个相关的表和一个不相关的表中的特定词的搜索功能。主表和登记表是相关的,且车辆表没有关系其他两个表。我试着处理这个问题的多种方法,但其中的非工作过。下面是有问题的代码。
我至今尝试过被放置视图模型中的三个表和我的控制器搜索方法中调用它。
Owner Table
public int OwnerId {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
Registration Table
public int RegistrationId {get; set;}
public DateTime RegisteredDate {get; set;}
public string RegistrationLocation {get;set;}
public int OwnerId {get;set;}
Vehicle Table
public int VehicleId {get;set;}
public string VehicleName {get;set;}
public DateTime VehicleYear {get;set;}
public string Model {get;set;}
SearchViewModel
public IEnumerable<Owner> Owners {get;set;}
public IEnumerable<Registration> Registrations {get;set;}
public IEnumerable<Vehicle> Vehicles {get;set;}
Controller
[HttpGet]
public SearchViewModel Search(string searchString)
{
SearchViewModel searchVM = new SearchViewModel();
searchVM.Owner = searchVM.Owner.Where(o => o.FirstName.Contains(searchString));
searchVM.Registration = searchVM.Registration.Where(r => r.RegistrationLocation.Contains(searchString));
searchVM.Vehicle = searchVM.Vehicle.Where(v =>
v.Model.Contains(searchString));
return searchVM;
}
我已经试过另一种方法是:
[HttpGet]
public IActionResult Search(string searchString)
{
var owner = from owners in _context.Owner select owners;
var registration = from registrations in _context.Registration select
registrations;
var vehicle = from vehicles in _context.Vehicle select vehicles;
owner = owner.Where(o => o.FirstName.Contains(searchString));
registration = registration.Where(r =>
r.RegistrationLocation.Contains(searchString));
vehicle = vehicle.Where(v =>
v.Model.Contains(searchString));
return Ok(); //I'm not sure how to return the three.
}
结合您的两次尝试。在第一次尝试你建立一个视图模型,而不是查询数据库。在第二次尝试你查询的数据库,而不是建立一个视图模型。两者都做。
例如:
var searchVM = new SearchViewModel();
searchVM.Owners = _context.Owner.Where(o => o.FirstName.Contains(searchString));
searchVM.Registrations = _context.Registration.Where(r => r.RegistrationLocation.Contains(searchString));
searchVM.Vehicles = _context.Vehicle.Where(v => v.Model.Contains(searchString));
return searchVM;