我遇到一个问题,我无法将数据添加到表RepresentativeImages
,因为表中没有数据。在我的方法中:只有如果表包含数据,它将通过第一个if
语句并添加数据,但如果,则中没有数据表,它只会跳过if
语句。我从来没有处理过这样的问题,所以如果有人能告诉我为什么这样做我会非常感激!
这是我的网络服务的方法。 这是我的编码,我将展示具体问题所在。
public void UpdateRepresentative(RepresentativeView repView)
{
using (TruckDb db = new TruckDb())
{
Representative rep = (from x in db.Represetatives
where x.Id == repView.Id
select x).First();
rep.Id = repView.Id;
rep.Name = repView.Name;
rep.Surname = repView.Surname;
rep.Position = repView.Position;
rep.CellPhone = repView.CellPhone;
rep.WorkAddress = repView.WorkAddress;
rep.Email = repView.Email;
rep.OfficeLine = repView.OfficeLine;
rep.Fax = repView.Fax;
rep.Interest = repView.Interest;
rep.CustomerId = repView.CustomerId;
rep.Province = repView.Province;
//-----THE ISSUE LIES HERE-----
if (db.RepresentativeImages.Any(x => x.RepresentativeId != rep.Id))
{
var repImage = new RepresentativeImages
{
Image = repView.Image,
RepresentativeId = rep.Id
};
db.RepresentativeImages.Attach(repImage);
db.RepresentativeImages.Add(repImage);
}
else if (db.RepresentativeImages.Any(x => x.RepresentativeId == rep.Id))
{
RepresentativeImages repImage = (from x in db.RepresentativeImages
where x.RepresentativeId == rep.Id
select x).First();
repImage.Image = repView.Image;
db.RepresentativeImages.Attach(repImage);
var entryImage = db.Entry(repImage);
entryImage.State = EntityState.Modified;
}
db.Represetatives.Attach(rep);
var entry = db.Entry(rep);
entry.State = EntityState.Modified;
db.SaveChanges();
}
}
if
语句正在检查是否有任何ID与repId
匹配,如果它不匹配,则应逐步执行if
语句并实际添加新图像到桌子。
现在我知道问题的原因了。这是因为RepresentativeImages
表中还没有数据,因此无法找到与Id
匹配的任何repId
。即使表格中没有数据,我怎样才能将图像添加到表格中?
答案 0 :(得分:1)
从业务角度来看,您的第一个if
毫无意义。它应该是您的第二个if
的其他条款。
您的商业决策应如下所示:
如果此ID的图片已存在,请使用其他创建新图片。
所以:
if (db.RepresentativeImages.Any(x => x.RepresentativeId == rep.Id))
{
RepresentativeImages repImage = (from x in db.RepresentativeImages
where x.RepresentativeId == rep.Id
select x).First();
repImage.Image = repView.Image;
db.RepresentativeImages.Attach(repImage);
var entryImage = db.Entry(repImage);
entryImage.State = EntityState.Modified;
}
else
{
var repImage = new RepresentativeImages
{
Image = repView.Image,
RepresentativeId = rep.Id
};
db.RepresentativeImages.Attach(repImage);
db.RepresentativeImages.Add(repImage);
}