An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported

StackOverflow https://stackoverflow.com/questions/8051464

Frage

My project is divided to PresentationLayer, BusinesLogicLayer and DataAccessLayer. Every created object goes through these layers. In simplifying:

SetFilter.xaml.cs

FilterFactory fFactory = new FilterFactory();
Filter myFilter = fFactory.Create(someClient, time, message);
FilterBLO filterBLO = new FilterBLO();
filterBLO.Save(myFilter);

FilterBLO.cs

FilterDAO filterDAO = new FilterDAO();
using (TransactionScope transcope = new TransactionScope())
{
    filterDAO.Save(myFilter);
    transcope.Complete()
}

FilterDAO.cs

using(DBDataContext dbdc = new DBDataContext)
{
    dbdc.Filter.InsertOnSubmit(myFilter);
    changeSet = dbdc.GetChangeSet();
    dbdc.SubmitChanges()
}

Filter is connected with table Client using ClientFilter table containing FilterID and ClientID. (many-to-many relationship)

If I create new 3 objects everything's ok, but if I'm getting existing Client in database (also using ClientBLO and ClientDAO so in separate TransactionScope and separate DBDataContext) I get error:

An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.

(I searched other similar threads but I didn't found solution to my problem.)

And finally my question

How should I save myFilter if Client exists in database. I tried Attach() it to datacontext in FilterDAO.cs but I get the same error.

War es hilfreich?

Lösung

You have to obtain Client from the database with the same DataContext you use to InsertOnSubmit the Filter; then you have to set Client value in the Filter object with that object before InsertOnSubmit.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top