简体   繁体   中英

Insert/Update Many to Many in an Entity Framework 6 Jointable

I'm trying to inserting and updating in this EF6-MVC project, but I cannot do it properly. I really need your help guys, I'd appreciate it.

Let's say I have this 3 tables:

Class/Table 1: Curso --> CursoId - nombreCurso

Class/Table 2: Modalidad --> ModalidadId - nombreModalidad

Class/Table 3: ModalidadCurso --> ModalidadId - CursoId (EF Creates automatically)


Let's get just to the point, next model (simplified):

public class Curso
{
        public int CursoId{ get; set; }

        public string nombreCurso { get; set; }

        public virtual ICollection<Modalidad> Modalidades { get; set; }
}


public class Modalidad
{

        public int ModalidadId{ get; set; }

        public string nombreModalidad { get; set; }

        public virtual ICollection<Curso> Cursos { get; set; }
}



public class ItehlContext: DbContext
{
        public ItehlContext(): base("name=conexionItehl") { }

        public DbSet<Curso> Cursos { get; set; }

        public DbSet<Modalidad> Modalidades { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<Modalidad>()
             .HasMany(c => c.Cursos)
             .WithMany(i => i.Modalidades)
             .Map(t => t.MapLeftKey("codigoModalidad")
                 .MapRightKey("codigoCurso")
                 .ToTable("ModalidadCurso"));

        }
}

well, the thing is, I'm trying to do the next thing, EF6 is creating a ModalidadCurso table, where saves the ModalidadId & CursoId, as a many-many relationship where pass the FK of the classes.

But I'm having problems in my MVC-ViewForm when I'm trying to create a new Curso Entity, cause it does not create the ForeignKeys in the modalidadCurso entity as it should be expected. I been studing that little inconvenience for days, it simply doesn't work.

Controller Create GET/POST

    // GET: /Curso/Create
    public ActionResult Create()
    {
        var cursos = new Curso();
        cursos.Modalidades = new List<Modalidad>();
        ListaModalidadesDropDownList(cursos);
        return View();
    }

    // POST: /Curso/Create
    // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener 
    // más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="codigoCurso,nombreCurso")] Curso curso)
    {
        try
        {
            var nuevaModalidad = new List<Modalidad>();
            if (nuevaModalidad != null)
            {

                foreach (var modalidad in nuevaModalidad)
                {
                    var agregarModalidad = db.Modalidades.Find(modalidad);
                    curso.Modalidades.Add(agregarModalidad);

                }
            }

            if (ModelState.IsValid)
            {
                db.Cursos.Add(curso);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

        catch (RetryLimitExceededException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.)
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }

        ListaModalidadesDropDownList(curso.Modalidades.First().codigoModalidad);
        return View(curso);
    }

I got this:

Entity Insert Many-Many-Relationship

And it creates the entity in Curso Table, that's ok.

but, in the FK-Many Many Relationship-ModalidadCurso table, it doesn't do anything.

What am I doing wrong?? I'm a beginner in Entity Framework, but everything seems ok.

Thanks for the help.

This is the Create.cshtml file (simplified)

@model ItehlConsulting.Models.Itehl.Curso
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken() 
   l.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.nombreCurso, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.nombreCurso)
                @Html.ValidationMessageFor(model => model.nombreCurso)
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2" for="codigoModalidad">Modalidad</label>
            <div class="col-md-10">
                @Html.DropDownList("codigoModalidad", String.Empty)
                @Html.ValidationMessageFor(model => model.Modalidades.First().nombreModalidad)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Crear Curso" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

In your view, you are sending codigoModalidad and nombreCurso . You have to post these values to the controller.

Replace this:

public ActionResult Create([Bind(Include="codigoCurso,nombreCurso")] Curso curso)

for this:

public ActionResult Create(string nombreCurso, int codigoModalidad)

Then, inside your controller action, you have to create the Curso and relate it with Modalidad:

[HttpPost]
public ActionResult Create(string nombreCurso, int codigoModalidad)
{
    Modalidad modalidad = new Modalidad();
    modalidad.ModalidadId = codigoModalidad;
    //if modalidad already exists in database, and you just want to make a relationship
    ctx.Entry(modalidad).State = EntityState.Unchanged; 
    //if modalidad does not exists in database, and you want to insert it
    //ctx.Entry(modalidad).State = EntityState.Added;

    Curso curso = new Curso();
    curso.nombreCurso = nombreCurso;
    curso.Modalidades.Add(modalidad); //add our existing modalidad to our new course

    ctx.Cursos.Add(curso);
    ctx.SaveChanges();
}

EDIT 1

Inside Curso constructor:

public Curso() 
{
    Modalidades = new HashSet<Modalidad>();   
}

Inside Modalidad constructor:

public Modalidad()
{
     Cursos = new HashSet<Curso>();
}

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM