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

  • SEARCH
  • Home
  • 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 7619301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T03:39:11+00:00 2026-05-31T03:39:11+00:00

I am having a problem with Entity Framework in my MVC 3 application. I

  • 0

I am having a problem with Entity Framework in my MVC 3 application. I have a users table, which is only ever populated with a new user row when a machine entity is created by a user that hasn’t created any machines before, i.e. it only creates users it hasn’t seen before. Each user belongs to a sector (division of the company) which also must be set before the user and the machine are saved. I have a default sector that new users are assigned to (so that this may be changed later on).

I have some code in my machine controller class for the creation of new machines that looks like this:

    [HttpPost]
    public ActionResult Create(Machine machine)
    {
        if (ModelState.IsValid)
        {
            // work out if the user exists in the database already
            var users = userRepository.All.Where(u => u.Username == machine.User.Username);
            if (users.Count() == 0)
            {
                // if the user entry doesn't exist we have to create it assigning a default sector
                Sector defaultSector = null;
                var defaultSectors = sectorRepository.All.Where(s => s.IsDefaultForNewUsers);
                if (defaultSectors.Count() == 0)
                {
                    // jebus! no default sector, so create one
                    defaultSector = new Sector() { Name = "Default", IsDefaultForNewUsers = true };
                    sectorRepository.InsertOrUpdate(defaultSector);
                    sectorRepository.Save();
                }
                else
                {
                    defaultSector = defaultSectors.First();
                }

                machine.User.Sector = defaultSector;
            }
            else
            {
                machine.User = users.First();
            }

            machineRepository.InsertOrUpdate(machine);
            machineRepository.Save();
            return RedirectToAction("Index");
        }
        else
        {
            ViewBag.PossibleInstalledOS = installedosRepository.All;
            ViewBag.PossibleLicenceTypes = licencetypeRepository.All;
            ViewBag.PossibleUsers = userRepository.All;
            return View();
        }
    }

[Edit] Here is the body of the InsertOrUpdate method from my Machine repository:

    public void InsertOrUpdate(Machine machine)
    {
        if (machine.MachineId == default(int)) {
            // New entity
            context.Machines.Add(machine);
        } else {
            // Existing entity
            context.Entry(machine).State = EntityState.Modified;
        }
    }

The problem I’m having with this code is that when I save the machine, it keeps creating a new user even though that user is already in the system. The line that finds the user works and retrieves the user as I would expect but entity framework doesn’t seem to understand that I wish to use this user that I’ve found and not create a new one. So at the moment I have multiple identical users (except ID of course) in my users table. I want a one to many here so that multiple machines are owned by the same user.

Does anyone have any idea how I force entity framework to respect that there is already a user there that I want to tie the new machine to?

  • 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-31T03:39:12+00:00Added an answer on May 31, 2026 at 3:39 am

    You didn’t post the code for your InsertOrUpdate method but I suspect that that is where the problem is. I bet in that method at some point you do something equivalent to:

    context.Machines.Add(machine);
    

    When you call DbSet.Add (or change the state of an entity to Added) you are actually adding the whole graph to the context. This process will stop when it encounters an object that is being tracked by the context. So if you have a machine object that references a user object and neither of these objects are being tracked by the context, then both the machine object and the user object will be added to the context and end up in an Added state. EF will then insert them both as new rows in the database.

    What you need to do, which was alluded to in the other answer, is make sure than EF knows that an existing user object does exist in the database by making sure it’s state is Unchanged (or possibly Modified) and not Added when you save.

    There are various ways that you could accomplish this and it’s hard to know which is best for you without seeing more of how your app and repository work. One way is to make sure that the context used to query for the user is the same context as is used to save. This way EF will already be tracking the existing user object and will know not to add it when you call Add.

    Another way is to let your repository know somehow whether or not the user object is new. Often people use the primary key to determine this–a zero key indicates a new object, non-zero indicates an existing object. You could also pass a flag into your repository.

    You can then call Add to add the graph, but then set the state of the User object to Unchanged (or Modified if it might have been changed since it was queried) if it is an existing user. This will prevent EF from inserting a new user into the database.

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

Sidebar

Related Questions

I'm having a small problem with ASP.NET MVC and Entity Framework 4. I have
I'm having a strange problem with new Entity Framework for .NET 4 I have
I have a problem in Entity-Framework, using Code-First, that I couldn't solve. Having entities
I'm working with the Entity Framework and I'm having a problem: When I try
We are having problem with the server migration. We have one application that are
Entity Framework 4 - STE - simple DB with single table Blogs having BlogID
I having a weird problem with Entity Framework with MySql database. Here's the code
I'm having a problem with the Entity Framework (EF4.1 - CodeFirst) It's basically duplicating
I'm using the entity framework and I have some properties which are common to
I'm having a problem with primary keys in Entity Framework when using SQLite. SQLite

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.