C# 如果表不包含任何数据,则无法添加数据
我遇到一个问题,无法将数据添加到表C# 如果表不包含任何数据,则无法添加数据,c#,.net,linq,C#,.net,Linq,我遇到一个问题,无法将数据添加到表RepresentativeImages,因为表中没有数据。在我下面的方法中:仅当表包含数据时,它将通过第一个if语句并添加数据,但如果表中还没有数据,它将跳过if语句。我从来没有处理过这样的问题,所以如果有人能告诉我它为什么这样做,我将非常感谢 这是我的web服务中的一个方法。 这是我的代码,我将说明具体问题所在 public void UpdateRepresentative(RepresentativeView repView) { using (
RepresentativeImages
,因为表中没有数据。在我下面的方法中:仅当表包含数据时,它将通过第一个if
语句并添加数据,但如果表中还没有数据,它将跳过if
语句。我从来没有处理过这样的问题,所以如果有人能告诉我它为什么这样做,我将非常感谢
这是我的web服务中的一个方法。
这是我的代码,我将说明具体问题所在
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
语句正在检查是否有与repId
匹配的Id,如果不匹配,则应单步执行if
语句,并实际向表中添加新图像
现在我知道问题的原因了。这是因为
RepresentativeImages
表中还没有数据,所以它找不到任何Id
与repId
匹配。即使我的表中还没有数据,我怎样才能将图像添加到我的表中?如果从业务角度看,您的第一个毫无意义。它应该是第二个if
的else子句
您的业务决策应如下所示:
如果此id的图片已经存在,请使用该图片,否则创建一个新的
因此:
u应该在caseTable.Rows.Count==0的情况下排除if语句!谢谢你指给我看,伙计。它现在可以正常工作:)
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);
}