-1

I have classes..

CONSUL_CA_Aluno:

public class CONSUL_CA_Aluno
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public int Cpf { get; set; }
    public string Email { get; set; }
    public string Senha { get; set; }
    public int Ativo { get; set; }

    public virtual ICollection<CONSUL_CA_Curso> CONSUL_CA_Cursos { get; set; }
}

CONSUL_CA_Curso:

public class CONSUL_CA_Curso
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public int Ativo { get; set; }
    public string Ministrante { get; set; }
    public string Duracao { get; set; }
    public int CargaHoraria { get; set; }
    public string LocalCurso { get; set; }

    public ICollection<CONSUL_CA_Aluno> CONSUL_CA_Alunos { get; set; }
}

In bd I have the table CONSUL_CA_CursoAluno.

But, when I test:

CONSUL_CA_Aluno aluno = new CONSUL_CA_Aluno();
aluno.Ativo = 1;
aluno.Cpf = 1321;
aluno.Email = "email";
aluno.Nome = "diididid";
aluno.Senha = "123";
aluno.CONSUL_CA_Cursos = contexto.Cursos.ToList();
aluno.CONSUL_CA_Cursos = aluno.CONSUL_CA_Cursos.Select(curso => contexto.Curso.FirstOrDefault(x => x.Id == curso.Id)).ToList();
contexto.Aluno.Add(aluno);
contexto.SaveChanges();

Show the error:

An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll Additional information: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
user3324749
  • 103
  • 6
  • This question has been answered before in http://stackoverflow.com/questions/19342908/entity-framework-many-to-many-mapping – Daniel Uribe May 05 '14 at 20:01
  • 1
    **See the InnerException for details** – Gert Arnold May 05 '14 at 20:09
  • possible duplicate of [DbUpdateException with entities that do not expose foreign key properties](http://stackoverflow.com/questions/10113323/dbupdateexception-with-entities-that-do-not-expose-foreign-key-properties) – Gert Arnold May 07 '14 at 12:50

1 Answers1

1

You probably did not configure the many-to-many relationship. In your DbContext paste something like this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CONSUL_CA_Aluno>() 
           .HasMany(t => t.CONSUL_CA_Cursos) 
           .WithMany(t => t.CONSUL_CA_Alunos)

        base.OnModelCreating(modelBuilder);
    }

Details on that are provided here: http://msdn.microsoft.com/en-us/data/jj591620.aspx#ManyToMany

mr100
  • 4,340
  • 2
  • 26
  • 38