我有一个结合了Residents和Requests表的linq语句
var resident = await _context.Resident
.Include(s => s.Requests)
.FirstOrDefaultAsync(m => m.ID == id);
问题在于,即使与住户无关的所有请求也会出现。
我尝试添加Where语句,但仍然获得所有请求。
var resident = await _context.Resident
.Include(s => s.Requests)
.Where(s =>s.UserID == "f7c6ceef-663f-48af-9a84-b0a3d2a97601")
.FirstOrDefaultAsync(m => m.ID == id);
作为参考,这是常驻模型类
public class Resident
{
public Resident()
{
this.CreatedAt = DateTime.Now;
}
public int ID { get; set; }
public string UserID { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[Required]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[Display(Name = "Number of Cameras")]
public int CameraQty { get; set; }
public DateTime CreatedAt { get; set; }
public string Latlng { get; set; }
public ICollection<Camera> Cameras { get; set; }
public ICollection<Request> Requests { get; set; }
}
这是请求模型类
using System.ComponentModel.DataAnnotations;
namespace MVC_NeighbourhoodCamera.Models
{
public class Request
{
public Request()
{
this.CreatedAt = DateTime.Now;
}
public int ID { get; set; }
public int ResidentID { get; set; }
public string UserID { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
[DataType(DataType.MultilineText)]
public string Details { get; set; }
public Boolean Completed { get; set; }
public Boolean Active { get; set; }
public DateTime CreatedAt { get; set; }
public Resident Resident { get; set; }
}
}
答案 0 :(得分:0)
您没有在Resident-> Requests一对多关系中正确设置外键。
通过添加Request
来修复ForeignKeyAttribute
类,如下所示(+进行迁移并将其运行到数据库中):
public class Request
{
//Other properties
..
public int ResidentID { get; set;}
ForeignKey["ResidentID"]
public Resident Resident { get; set;}
}
可以找到更多信息,例如here。