LINQ cannot remove an entity that has not been attached error solution)

Source: Internet
Author: User

The following error occurs during the Ling operation:

Cannot remove an entity that has not been attached

My error is that different data context is used for query and deletion in the same method.

ErrorCodeAs follows:

Protected Dataclassesdatacontext DB
{
Get
{
Return   New Dataclassesdatacontext ();
}
}

  Private   Void Deleteogu ( Int ID)
{
VaR OGU = DB. Ogus. firstordefault (x => X. ogu_sysid = ID );

DB. Ogus. deleteonsubmit (OGU );

DB. submitchanges ();

Binddata ();
}

In the delete method, DB is a new instance every time. Therefore, the parameter OGU of deleteonsubmit is not in the same object as the data context of the method, and an error is displayed as shown in the title.

 Remove the DB attribute and move it to the delete method.

  Private   Void Deleteogu ( Int ID)
{
VaR DB =   New Dataclassesdatacontext ();

VaR OGU = DB. Ogus. firstordefault (x => X. ogu_sysid = ID );

DB. Ogus. deleteonsubmit (OGU );

DB. submitchanges ();

Binddata ();
}

In this case, all the databases in the method point to the same object, and errors are excluded.

 

From: http://blog.csdn.net/duwa789/archive/2010/05/06/5563714.aspx

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.