简体   繁体   English

在实体框架中多对多插入/更新6可联接

[英]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. 我正在尝试在此EF6-MVC项目中进行插入和更新,但是我无法正确执行。 I really need your help guys, I'd appreciate it. 我真的需要您的帮助,我将不胜感激。

Let's say I have this 3 tables: 假设我有以下3个表:

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

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

Class/Table 3: ModalidadCurso --> ModalidadId - CursoId (EF Creates automatically) 类/表3:ModalidadCurso-> ModalidadId-CursoId(EF自动创建)


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. 好吧,事情是,我正在尝试做下一件事,EF6正在创建一个ModalidadCurso表,将ModalidadId和CursoId保存为其中通过类的FK的多对多关系。

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. 但是,当我尝试创建新的Curso实体时,我在MVC-ViewForm中遇到问题,因为它没有在modalidadCurso实体中创建ForeignKeys。 I been studing that little inconvenience for days, it simply doesn't work. 我一直在研究几天的不便之处,但这根本行不通。

Controller Create GET/POST 控制器创建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. 并在Curso Table中创建实体,没关系。

but, in the FK-Many Many Relationship-ModalidadCurso table, it doesn't do anything. 但是,在FK-Many Many Relationship-ModalidadCurso表中,它什么也没做。

What am I doing wrong?? 我究竟做错了什么?? I'm a beginner in Entity Framework, but everything seems ok. 我是Entity Framework的初学者,但是一切似乎都还不错。

Thanks for the help. 谢谢您的帮助。

This is the Create.cshtml file (simplified) 这是Create.cshtml文件(简体)

@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 . 在您看来,您正在发送codigoModalidadnombreCurso 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: 然后,在控制器动作中,您必须创建Curso并将其与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 编辑1

Inside Curso constructor: 内部Curso构造函数:

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

Inside Modalidad constructor: 内部Modalidad构造函数:

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

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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