簡體   English   中英

在實體框架中多對多插入/更新6可聯接

[英]Insert/Update Many to Many in an Entity Framework 6 Jointable

我正在嘗試在此EF6-MVC項目中進行插入和更新,但是我無法正確執行。 我真的需要您的幫助,我將不勝感激。

假設我有以下3個表:

類/表1:Curso-> CursoId-nombreCurso

類/表2:Modalidad-> ModalidadId-nombreModalidad

類/表3:ModalidadCurso-> ModalidadId-CursoId(EF自動創建)


讓我們直接講一下下一個模型(簡化):

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"));

        }
}

好吧,事情是,我正在嘗試做下一件事,EF6正在創建一個ModalidadCurso表,將ModalidadId和CursoId保存為其中通過類的FK的多對多關系。

但是,當我嘗試創建新的Curso實體時,我在MVC-ViewForm中遇到問題,因為它沒有在modalidadCurso實體中創建ForeignKeys。 我一直在研究幾天的不便之處,但這根本行不通。

控制器創建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);
    }

我懂了:

實體插入多對多關系

並在Curso Table中創建實體,沒關系。

但是,在FK-Many Many Relationship-ModalidadCurso表中,它什么也沒做。

我究竟做錯了什么?? 我是Entity Framework的初學者,但是一切似乎都還不錯。

謝謝您的幫助。

這是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>

在您看來,您正在發送codigoModalidadnombreCurso 您必須將這些值發布到控制器。

替換為:

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

為了這:

public ActionResult Create(string nombreCurso, int codigoModalidad)

然后,在控制器動作中,您必須創建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();
}

編輯1

內部Curso構造函數:

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

內部Modalidad構造函數:

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

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM