I have two tables, Promotion and PromotionLine, with a foreign key defined as PromotionLine.PromoID = Promotion.ID
PromotionLines are associated with the Promotion model with the following in the Promotion class:
public IList<PromotionLine> PromotionLineItems { get; set; }
I chose not to use virtual because I don't want the promo lines loaded if we're just using a summary view to show high level Promotion info (such as a list of Promotions).
When promotion details are needed, I get the promotion lines:
public static Promotion GetInstance(int? promotionId)
{
if (promotionId == null) return null;
using (APP01Entities entities = new APP01Entities())
{
return entities.Promotions
.Include(s => s.PromotionState)
.Include(h => h.PromotionHeaderType)
.Include(l => l.PromotionLineItems)
.Include(c => c.PromotionComments)
.FirstOrDefault(p => p.ID == promotionId);
}
}
This works, and I can access the promotion lines in my view.
However, when I go to update changes, I encounter the error:
“A referential integrity constraint violation occurred: The property
value(s) of 'Promotion.ID' on one end of a relationship do not match
the property value(s) of 'PromotionLine.PromotionID' on the other
end.”
I understand WHY this error is occurring. I don't know how to get around it.
I'm using the default update method (created by EF scaffolding):
public bool Update()
{
try
{
using (APP01Entities entities = new APP01Entities())
{
entities.Promotions.Attach(this);
var entity = entities.ChangeTracker.Entries<Promotion>().FirstOrDefault(e => e.Entity == this);
if (entity == null)
{
return false;
}
entity.State = EntityState.Modified;
entities.SaveChanges();
}
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
throw e.Improve();
}
}
The problem is with:
entities.Promotions.Attach(this);
"this" has the promotion lines. entities.Promotions does not.
Here is how I'm calling the update method:
[HttpPost]
public ActionResult Edit(Promotion promotion)
{
if (ModelState.IsValid)
{
promotion.Update();
}
return View(promotion);
}
Questions
- How do I get the promotion lines added to entities.Promotions?
- or, should I be approaching this update differently?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…