Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6042103
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T06:45:11+00:00 2026-05-23T06:45:11+00:00

What is the correct way to insert/update a row using Entity Framework? I know

  • 0

What is the correct way to insert/update a row using Entity Framework?

I know this 3 methods:

1 – using Attach

var newSale = _context.ST_Sales.FirstOrDefault(x => x.SaleId == saleId);
newSale.Hours = 2;
_context.ST_Sales.Attach(newSale);
_context.ObjectStateManager.ChangeObjectState(newSale, EntityState.Modified);
_context.SaveChanges();

2 – using ApplyCurrentValues

var newSale = _context.ST_Sales.FirstOrDefault(x => x.SaleId == saleId);
newSale.Hours = 2;
_context.ST_Sales.ApplyCurrentValues(newSale);
_context.SaveChanges();

3 – using EF logic

var newSale = _context.ST_Sales.FirstOrDefault(x => x.SaleId == saleId);
newSale.Hours = 2;
_context.SaveChanges(); // EF tracks the newSale obj and knows that was changed

And to insert there are one more method witch uses the AddObject

var newSale = new ST_Sales();
newSale.Hours = 2;
_context.ST_Sales.AddObject(newSale);
_context.SaveChanges();

The problem I’m facing is an error on the EF saying that the modified row is still in memory.

My scenario:

  • 20 users can add sales to their own company.

I have a simple table relation:

tbl_Companies { CompanyId, Name }
tbl_Sales     { CompanyId, Hours, Amount }

my Edit View simple get’s a sales collection of the current week as

var model = _context.ST_Sales.Where(x => x.CompanyId == 2);
return View(model);

and on the HttpPost Action I simply loop through each one and save the db changes like

[HttpPost]
public ViewResult Index(List<ST_Sales> model)

and

bool newSale = false;
foreach( var s in model ) { // let's loop through all

    newSale = false;

    var sale = _context.ST_Sales.FirstOrDefault(x => x.SaleId == s.SaleId);
    if( sale == null) {

        // sale was not found, let's add it (this happens for todays date
        //    as there is no info yet in the db, but we need to add today's info)

        sale = new ST_Sale();
        sale.Company.Id = currentLoggedInUser.companyId;

        newSale = true;  // let's say it's a new sale so we can add the new object to the changes to commit
    }

    sale.Hours = s.Hours;
    sale.Amount = s.Amount;

    if( newSale ) {
        // it's a new sale, let's add the obj to our Entity
        _context.ST_Sales.AddObject(sale);
    } 
    else {
        // no need to do anything, EF is tracking the changes of existing objects
    }
}

_context.SaveChanges();

This works fine for one user… but if I logout and login with a different user, and I can see in the breakpoint that the companyId value is different, soon I commit the changes to be saved I get the weird error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

What am I doing wrong?


I’m creating a new instance in the Controller level like:

public class SalesController : Controller
{
    private SalesTrackerRepository db = SalesTrackerRepository.Instance;

    ...
}

and using the source from Sams Code


Also, I used Rick Strahl code and ending up using:

public class SalesController : Controller
{
    private SalesTrackerRepository db = 
            SalesTrackerRepositoryFactory.GetWebRequestScopedDataContext<SalesTrackerRepository>();

    ....

}

And I keep getting the same error 🙁


My tests are based in the same machine using Chrome and Opera with both different credentials.

How can I get this error on such test?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T06:45:12+00:00Added an answer on May 23, 2026 at 6:45 am

    Got the bugger!

    I was using MemoryCache to cache some results and realized that I was using that cache to request an EntityKey.

    My advise: Please check if in your project you really want to deal with all this workarounds!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What is the correct way to do this? For example, how would I change
What is the correct way to import a C++ class from a DLL? We're
What is the correct way to check if a value is a date/number in
Is there a correct way in Windows Forms to flash a titlebar without having
What is the correct way to convert ASP.NET SOAP-based web services to JSON-based responses?
What is the 'correct' way to store a native pointer inside a Java object?
What is the correct way of retrieving maximum values of all columns in a
What is the correct way of iterating over a vector in C++? Consider these
What is the correct way to work with SQLite in WPF and ASP.NET MVC?
What is the correct way to separate between F1 and i.e. CTRL + F1

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.