问题描述
这是我得到的例外:
System.ArgumentException: '包含路径表达式必须引用一个 类型上定义的导航属性。使用虚线路径 参考导航属性和集合的 Select 操作符 导航属性。参数名称:路径'
基本上,我有一个我想传递的客户模型,它有 3 个外键(Human、Member、Contact),并且 Contact 有一个 ICollection 位置,它是 Contact Model 的外键。我正在尝试将所有内容发送到视图(包括位置),但出现此错误。我是否必须制作一个 viewmodel 才能实现它,我错过了什么?这些是代码:
public class Customer
{
public int ID { get; set; }
public int HumanID { get; set; }
public int MemberID { get; set; }
public int ContactID { get; set; }
public Human Human { get; set; }
public Member Member { get; set; }
public Contact Contact { get; set; }
}
public class Contact
{
public int ID { get; set; }
[required(ErrorMessage = "E-mail is required")]
[DataType(DataType.EmailAddress)]
[display(Name = "E-mail")]
public string Email { get; set; }
[required(ErrorMessage = "Phone Number is required")]
[display(Name = "Phone Number")]
public List<string> PhoneNumber { get; set; }
public int LocationID { get; set; }
//One user might have many register locations
public virtual ICollection<Location> Locations { get; set; }
}
public ActionResult Index()
{
var customers = db.Customers.Include(c => c.Contact)
.Include(c => c.Human).Include(c => c.Member)
.Include(c => c.Contact.Locations
.Where(l => l.ID == c.Contact.LocationID));
return View(customers.ToList());
}
我应该澄清一下,我在运行程序并尝试转到视图时遇到了异常。先谢谢大家!
解决方法
当提供给方法的参数之一无效时,将引发此异常。这意味着它有一个空值。由于您不允许将空值传递给视图,因此您必须确保模型中没有空值。
如果您想允许在模型中传递空列,您应该在每列的数据类型前添加 ?
,如下所示:-
public class Customer
{
public int ID { get; set; }
public int? HumanID { get; set; }
public int? MemberID { get; set; }
public int? ContactID { get; set; }
public Human Human { get; set; }
public Member Member { get; set; }
public Contact Contact { get; set; }
}
这将应用于主要请求模型中包含 (.include()
) 的每个模型。
假设您已经创建了其他实体并验证了外键是否存在。您不能在属性的属性上使用 .Include
,您必须使用 .ThenInclude()
。您也不能在 Where
中包含 .Include
。我会使用 .Select
var customers = db.Customers
.Include(c => c.Contact)
.ThenInclude(c => c.Location)
.Include(c => c.Member)
.Include(c => c.Human);