I get this error
Cannot add an entity with a key that is already in use
when I try to save an Item
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Item item)
{
Global.DataContext.Items.Attach(item);
Global.DataContext.SubmitChanges();
return View(item);
}
That's because I cannot attach the item to the global DataContext.
Is it possible to save an item without creating a new DataContext, and without having to assign each field of the item manually?
(I am very new to LINQ)
EDIT: I realised static DataContext would cause problems thanks to the comments below, it is now like this
public static AbcDataContext DataContext
{
get
{
if (!HttpContext.Current.Items.Contains("DataContext"))
HttpContext.Current.Items["DataContext"] = new AbcDataContext(ConnectionString);
return (AbcDataContext)HttpContext.Current.Items["DataContext"];
}
}
(Rex might not agree to that, but I can't be bothered changing the whole code at the moment - may be later)
Don't have a global/static DataContext, that is setting yourself up for pain. A DataContext should represent a single logical transaction ("get in, do x/y/z and get out"). They are cheap to create and easy to dispose; there is absolutely no reason to try to minimize them, much less keep a global/static one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With