ASP.Net MVC - 多对多CRUD

时间:2017-11-22 17:12:49

标签: asp.net-mvc entity-framework many-to-many crud

我是ASP.Net MVC的新手,我在使用多对多CRUD时遇到了一些问题。 我需要在两个表之间创建一个N:N,并在创建两个类型之前创建一个条目。

我有以下代码:

[Table("DadosOperacao")]
public class Operacao : IIdentificado
{
    Properties Here...

    /* Foreign Key Operacao */
    public virtual ICollection<OperacaoParte> ParteGroup { get; set; }
}

[Table("DadosParte")]
public class Parte : Pessoa
{
    Properties Here...

    /* Foreign Key Operacao */
    public virtual ICollection<OperacaoParte> OperacaoGroup { get; set; }
}

[Table("OperacaoParte")]
public class OperacaoParte
{
    [Key]
    [Column(Order = 0)]
    [ForeignKey("Operacao")]
    public int OperacaoID { get; set; }

    [Key]
    [Column(Order = 1)]
    [ForeignKey("Parte")]
    public int ParteID { get; set; }

    public virtual Operacao Operacao { get; set; }

    public virtual Parte Parte { get; set; }

    public int IDTipoParte { get; set; }
}

编辑: 我用

映射了我的字段
modelBuilder.Entity<OperacaoParte>()
    .HasKey(um => um.OperacaoParteID)
    .ToTable("OperacaoParte");

modelBuilder.Entity<OperacaoParte>()
    .HasRequired(um => um.Parte).WithMany(g => g.OperacaoGroup)
    .HasForeignKey(um => um.OperacaoID);

modelBuilder.Entity<OperacaoParte>()
    .HasRequired(um => um.Operacao).WithMany(g => g.ParteGroup)
    .HasForeignKey(um => um.ParteID);

我在控制器中的行动

[RequiresLogin]
[HttpPost]
public ActionResult ManytoMany(OperacaoParte Data)
{
    ActionResult Saida;

    AfortContext Banco = AfortContext.Conectar();

    var Operacao = Banco.Operacoes.Where(m => m.ID == 1)
        .SingleOrDefault();
    var Parte = Banco.Partes.Where(c => c.CPF == 43143336854.ToString())
        .SingleOrDefault();
    if (Operacao != null && Parte != null)
    {
        var OperacaoParte = new OperacaoParte
        {
            Operacao = Operacao,
            Parte = Parte,
            OperacaoID = Operacao.ID,
            ParteID = Parte.ID,
            IDTipoParte = Parte.IDTipoParte
        };
        Banco.OperacaoParte.Add(OperacaoParte);
        Banco.SaveChanges();
    }
    Saida = RedirectToAction("Index", "Operacao");
    return Saida;
}

但是当我尝试更新数据时,我收到以下错误

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries.
See the inner exception for details.System.Data.Entity.Core.UpdateException: 
An error occurred while updating the entries.See the inner exception for details.System.Data.SqlClient.
SqlException: 
Invalid column name 'OperacaoID'.
Invalid column name 'ParteID'.
Invalid column name 'IDTipoParte'.
Invalid column name 'OperacaoParteID'.
Invalid column name 'OperacaoParteID'.

我做错了什么?

0 个答案:

没有答案