運行我的get方法在我的控制器列表時,我有以下錯誤:查找數據
指定的LINQ表達式包含引用是查詢與不同的上下文相關聯。
已經調試控制器它是產生錯誤的排序依據語句
方法是:
public ActionResult OwnerList()
{
var owners = (from s in db.Owners
orderby Peopledb.Posts.FirstOrDefault(x => x.PostId == s.PostId).PostName
select s).ToList();
var viewModel = owners.Select(t => new OwnerListViewModel
{
Created = t.Created,
PostName = Peopledb.Posts.FirstOrDefault(x => x.PostId == t.PostId).PostName,
Dormant = t.Dormant,
OwnerId = t.OwnerId,
});
return PartialView("_OwnerList", viewModel);
}
在第一數據庫owner的類是,的DbContext = IARContext:
public class Owner
{
public int OwnerId { get; set; }
[Column(TypeName = "int")]
public int PostId { get; set; }
[Column(TypeName = "bit")]
public bool Dormant { get; set; }
[Column(TypeName = "datetime2")]
public DateTime Created { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
public People.Models.Post Post { get; set; }
}
第二個數據庫中的Post類是dbcontext = PeopleContext:
public class Post
{
public int PostId { get; set; }
[StringLength(50)]
[Column(TypeName = "nvarchar")]
public string PostName { get; set; }
[Column(TypeName = "bit")]
public bool Dormant { get; set; }
[StringLength(350)]
[Column(TypeName = "nvarchar")]
public string Description { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
public virtual ICollection<Owner> Owners { get; set; }
}
我試圖從帖子查找PostName在人民DB從IAR分貝
從s在db.Owners 排序依據s.Post.PostName 這將期待您的數據庫中POST表。如果它不存在,它會拋出這個錯誤,你不得不在 – DevilSuichiro
之間切換上下文感謝有道理,我該怎麼做? –
'Peopledb.Posts.FirstOrDefault(x => x.PostId == t.PostId).PostName'有一天會給你一個'NullReferenceException' ... –