这是我的模特
@foreach (var k in Model.AllJobs)
{
<div class="panel panel-default instructions">
<div class="panel-body">
<span>Date: @k.date.ToShortDateString() From: @k.timeFrom Until: @k.timeUntil</span>
<span>Price: @k.Cleaner.Price</span>
<span>Total: </span>
</div>
</div>
<br />
}
在我看来,我试图访问'Cleaner'中的属性
{{1}}
但我收到错误
对象引用未设置为对象的实例。
如果将'Cleaner'与'PostJob'一起加载,为什么会出现此错误?
这是数据库中的postjob
答案 0 :(得分:0)
我认为您需要使用Include()
作为回报
return context.PostJobs.Include(x=>x.Cleaner).Where(r => r.userId == id).ToList();
你的方法将是
public IEnumerable<PostJob> GetAllJobsByUserId(int id)
{
using (var context = new CleanerDataContext(@"Data Source=.\sqlexpress;Initial Catalog='Cleaning Lady';Integrated Security=True"))
{
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<PostJob>(c => c.Cleaner);
loadOptions.LoadWith<PostJob>(c => c.User);
context.LoadOptions = loadOptions;
return context.PostJobs.Include(x=>x.Cleaner).Where(r => r.userId == id).ToList();
}
}
别忘了包含
using System.Data.Entity;