如果您一次添加多个相关实体,您应该在每次之后调用SaveChanges,还是可以执行一次?我收到一个错误,例如“违反PRIMARY KEY约束”。
订单具有实体记录的导航属性。 我想将记录添加到订单,然后调用savechanges。 当我这样做时,我收到错误抱怨记录上的主键。
我想做这样的事情
Order o = new Order{.......}
Record r1 = new Record{...}
Record r2 = new Record{....}
o.Records.Add(r1)
o.Records.Add(r2)
Context.Orders.Add(o);
Context.SaveChanges()
这不是正确的方法吗?
...
//populate order entity
Order o = new Order { AccountKey = iAccnt, OfficeKey = iOffice, UserKey = iUser, CreatedDate = dtCreateDate };
//save
ctx.Orders.Add(o);
//locations
Location origin = new Location
{
Order = o,
LocationTypeKey = ctx.LocationTypes.Where(a => a.TypeName == "Origin").First().LocationTypeId,
Address1 = " test address 1",
Address2 = " test Address 2",
City = oi.OriginCity,
StateKey = ctx.States.Where(a => a.StateName == oi.OriginState).First().StateId,
CountryKey = ctx.Countries.Where(a => a.CountryName == oi.OriginCountry).First().CountryId
};
Location destn = new Location
{
Order = o,
LocationTypeKey = ctx.LocationTypes.Where(a => a.TypeName == "Destination").First().LocationTypeId,
Address1 = " test address 1",
Address2 = " test Address 2",
City = oi.OriginCity,
StateKey = ctx.States.Where(a => a.StateName == oi.DestinationState).First().StateId,
CountryKey = ctx.Countries.Where(a => a.CountryName == oi.DestinationCountry).First().CountryId
};
try
{
int rows = ctx.SaveChanges();
if (rows == 0)
{
retval = false;
}
}
catch (DbEntityValidationException ex)
{
string exst = ex.ToString();
}