我遇到了一个奇怪的错误,让我有点困惑,所以让我画图:
我有一个控制器,可以用房屋评论更新数据库。如果房子不存在,它会创建一个然后更新它。
所以这是如果房子不存在的代码:
if (checkHouse == null)
{
var department = db.Universitys.Single(d => d.universityName == "NotSet");//make dynamic
var hws = new House();
hws.address1 = reviewmodelview.Address1;
hws.address2 = reviewmodelview.Address2;
hws.postCode = reviewmodelview.postCode;
hws.noOfDisputes = 0;
department.Houses.Add(hws);
db.SaveChanges(); //created the house and saved the changes, now apply the review to it.
var theHouse = db.Houses.Single(d => d.address1 == reviewmodelview.Address1);//findhouse
var rvw = new Review(); //create review
rvw.condition = reviewmodelview.condition;
rvw.furniture = reviewmodelview.furniture;
rvw.overall = reviewmodelview.overall;
rvw.isApproved = false;
rvw.review = reviewmodelview.review;
rvw.user = User.Identity.Name;
rvw.reviewDate = DateTime.Now;
theHouse.Reviews.Add(rvw);
db.SaveChanges();
}
这是房子是否存在的代码:
else
{
var theHouse = db.Houses.Single(d => d.address1 == reviewmodelview.Address1);//findhouse
var rvw = new Review();//create review
rvw.condition = reviewmodelview.condition;
rvw.furniture = reviewmodelview.furniture;
rvw.overall = reviewmodelview.overall;
rvw.isApproved = false;
rvw.review = reviewmodelview.review;
rvw.user = User.Identity.Name;
rvw.reviewDate = DateTime.Now;
theHouse.Reviews.Add(rvw);
db.SaveChanges();
}
现在的问题是,如果房子存在,则添加评论。如果房子不存在,则将房子添加到数据库中,但代码在以下位置中断:
theHouse.Reviews.Add(rvw);
如果我将鼠标悬停在评论上,它会说它为空。错误是“对象引用未设置为对象的实例”。
但是,如果我再试一次,但这次添加数据库中已经存在的房子的地址,并在
theHouse.Reviews.Add(rvw);
它说:{System.Data.Objects.DataClasses.EntityCollection<Data.Manager.Review>}
我无法弄清楚为什么评论集合对于两段相同的代码是空的!
房子模型是这样的:
namespace Data.Manager
{
public class House
{
public virtual int HouseID { get; set; }
public virtual string postCode { get; set; }
public virtual string address1 { get; set; }
public virtual string address2 { get; set; }
public virtual int noOfDisputes { get; set; } //number of disputes added by tennants
public virtual int averageRating { get; set; }
public virtual ICollection<Review> Reviews { get; set; }
}
}
如果我能解释为什么会这样,我会永远爱你。