Entity Framework guarda duplicados de un lado en uno a muchos

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:

    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 };
                    defaultSector = defaultSectors.First();

                machine.User.Sector = defaultSector;
                machine.User = users.First();

            return RedirectToAction("Index");
            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
        } 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?

preguntado el 09 de marzo de 12 a las 13:03

2 Respuestas

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:


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.

respondido 11 mar '12, 18:03

that's a great explanation thanks. I've gone down the route of detecting if the ID is non-zero and setting the state to unchanged. The unfortunate side effect of this is that my InsertOrUpdate method is now detecting a number of dependent entities to ensure they are not new, which is muddying the waters somewhat. Is there any way you can nail down which entities a repository should care about, i.e. I don't want my machines repo dealing with user entities - I want to do that explicitly. - A. Murray

EF doesn't really work that way. It deals with graphs of entities, rather than individual entities. It's often useful to think in terms of aggregates (a concept popularised by DDD: en.wikipedia.org/wiki/Domain-driven_design) and have repositories that deal with aggregates rather than individual entities. One reason for this is that dealing with individual entities tends to fall down and/or get complicated as soon as the relationships between those entities need to be manipulated. - Arturo Vickers

Can you double check that your repositories are using the same data context? If not, you are essentially adding a new User entidad a la machineRepository. Alternatively you could attach the user to the context for the machine repository, but you'll likely keep running into bugs like this.

respondido 09 mar '12, 13:03

That might explain it. I have scaffolded my application thusfar but I have scaffolded each entity in turn with the repository option. It appears it places a private instance of the context inside each repository. I should really create a singleton from this? - A. Murray

@A.Murray Don't use a singleton or you'll run into tons of issues across multiple threads (requests). There are lots of ways to manage scope, but the simplest is to use dependency injection and let the IOC manage the scope. - Nick Larsen

I'm using ninject for injecting my repository implementations into my controller. Do I add another layer of DI to inject my context into my repositories? - A. Murray

@A.Murray yes, absolutely. Even still there are multiple ways to handle the scoping of the data context. The easiest is to just bind it in the request context. Eventually we ended up writing an IDataContextManager which we inject that allows us to tighten up the scope even more, but that's not really necessary until you need more control than the request scoping. - Nick Larsen

Forgive my ignorance but this doesn't feel right to me. Currently my EF context object inherits from DbContext (basically because the scaffolder gave me that). The repositories call methods inherited from this base class so substituting an interface means I'd have to put the methods from DbContext that are used into the interface. I realise I will probably have to rewrite some of the scaffolded stuff though. I don't suppose you have a simple example so that I can understand your meaning? - A. Murray

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.