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 680293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T01:21:22+00:00 2026-05-14T01:21:22+00:00

I’m new to the entity framework and I’m really confused about how savechanges works.

  • 0

I’m new to the entity framework and I’m really confused about how savechanges works. There’s probably a lot of code in my example which could be improved, but here’s the problem I’m having.

The user enters a bunch of picks. I make sure the user hasn’t already entered those picks.
Then I add the picks to the database.

       var db = new myModel()
       var predictionArray = ticker.Substring(1).Split(','); // Get rid of the initial comma.

        var user = Membership.GetUser();
        var userId = Convert.ToInt32(user.ProviderUserKey);

        // Get the member with all his predictions for today.
        var memberQuery = (from member in db.Members
                         where member.user_id == userId
                         select new
                                    {
                                        member,
                                        predictions = from p in member.Predictions
                                                     where p.start_date == null
                                                     select p

                                    }).First();

        // Load all the company ids.
        foreach (var prediction in memberQuery.predictions)
        {
            prediction.CompanyReference.Load();
        }

 var picks = from prediction in predictionArray
                          let data = prediction.Split(':')
                          let companyTicker = data[0]
                          where !(from i in memberQuery.predictions
                                 select i.Company.ticker).Contains(companyTicker)
                          select new Prediction
                          {
                              Member = memberQuery.member,
                              Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
                              is_up = data[1] == "up",  // This turns up and down into true and false.
                          };


    // Save the records to the database.
    // HERE'S THE PART I DON'T UNDERSTAND.
    // This saves the records, even though I don't have db.AddToPredictions(pick) 
            foreach (var pick in picks)
            {
                    db.SaveChanges();
            }

// This does not save records when the db.SaveChanges outside of a loop of picks.
 db.SaveChanges();
 foreach (var pick in picks)
            {

            }

// This saves records,  but it will insert all the picks exactly once no matter how many picks you have.  
//The fact you're skipping a pick makes no difference in what gets inserted.
            var counter = 1;
            foreach (var pick in picks)
            {
                if (counter == 2)
                {
                    db.SaveChanges();
                }
                counter++;
            }

I’ve tested and the SaveChanges doesn’t even have to be in the loop.
The below code works, too.

foreach (var pick in picks)
            {
                   break;
            }

db.SaveChanges()

There’s obviously something going on with the context I don’t understand. I’m guessing I’ve somehow loaded my new picks as pending changes, but even if that’s true I don’t understand I have to loop over them to save changes.

Can someone explain this to me?

Here’s updated working code based on Craig’s responses:
1) Remove the Type then loop over the results and populate new objects.

var  picks = (from prediction in predictionArray
                        let data = prediction.Split(':')
                        let companyTicker = data[0]
                        where !(from i in memberQuery.predictions
                                select i.Company.ticker).Contains(companyTicker)
                        select new //NO TYPE HERE
                        {
                            Member = memberQuery.member,
                            Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
                            is_up = data[1] == "up",  // This turns up and down into true and false.
                        }).ToList();

            foreach (var prediction in picks)
            {
              if (includePrediction)
               {
                var p = new Prediction{
                  Member = prediction.Member,
                  Company = prediction.Company,
                  is_up = prediction.is_up
                 };
                db.AddToPredictions(p);
                }
            }

2) Or if I don’t want the predictions to be saved, I can detach the predictions.

foreach (var prediction in picks) {
                  if  (excludePrediction)
                  {
                      db.Detach(prediction)
                   }

}
  • 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-14T01:21:23+00:00Added an answer on May 14, 2026 at 1:21 am

    The reason is here:

                          select new Prediction
                          {
                              Member = memberQuery.member,
    

    These lines will (once the IEnumerable is iterated; LINQ is lazy) :

    1. Instantiate a new Prediction
    2. Associate that Prediction with an existing Member, *which is attached to db.

    Associating an instance of an entity with an attached entity automatically adds that entity to the context of the associated, attached entity.

    So as soon as you start iterating over predictionArray, the code above executes and you have a new entity in your context.

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

Sidebar

Ask A Question

Stats

  • Questions 357k
  • Answers 357k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The other answers are correct. Here is some code you… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer you ruin the noConflict concept by reassigning the jquery to… May 14, 2026 at 9:40 am
  • Editorial Team
    Editorial Team added an answer If you get that particular error, you don't actually have… May 14, 2026 at 9:40 am

Related Questions

No related questions found

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.