Search code examples
c#asp.net-mvcmany-to-manyentity-framework-6database-first

Manage EF6 database first many to many relationship


I have an EF6, MVC4 database first web application. The database model has some many to many relationships defined, and the .edmx model is showing them the right way. The trouble is when I try to make an insert to my database, I have no option to add the related entity object to the one that's being created. I can make individual inserts on each related table, but the one that's storing the many to many relationship does isn't written.

These are the conflicting models:

enter image description here

This is the script of the table that should store the many to many relation:

CREATE TABLE [dbo].[funcionalidad_perfil] (
[funcionalidad_id] bigint NOT NULL,
[perfil_id] bigint NOT NULL)

How should I do to save data to the "funcionalidad_perfil" table, if it wasn't created automagically?


Solution

  • After a week of being looking for the answer on internet, I tried again, made a roll-back on my code and found the answer. It's embarrasing how easy it was:

    when creating a "perfil" object (after the creation of a "funcionalidad"), all I have to do is set a property of the "perfil" object, using method Add, to add a new "funcionalidad" to the collection.

    Explanation: when creating the entities from the db, EF stores the many to many relationship between entities in both of them, in a EntityCollection property. All that is needed to use it is to add a new object to the collection. On the SaveChanges method the data is saved to both tables, the one where the new object is being saved and the one that stores the many-to-many relations.

    Code example:

    [HttpPost]
    public ActionResult Add(Perfil perfil)
    {
        if (ModelState.IsValid)
        {
            perfil.funcionalidad.Add(db.Funcionalidad.First());
            db.Perfil.AddObject(perfil);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(perfil);
    }