我上课..
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; }
}
在bd我有表CONSUL_CA_CursoAluno。
但是,当我测试时:
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();
显示错误:
EntityFramework.dll中发生未处理的“System.Data.Entity.Infrastructure.DbUpdateException”类型异常 附加信息:保存不公开其关系的外键属性的实体时发生错误。 EntityEntries属性将返回null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。有关详细信息,请参阅InnerException。
答案 0 :(得分:1)
您可能没有配置多对多关系。在你的DbContext中粘贴如下:
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);
}
此处提供了有关详细信息:http://msdn.microsoft.com/en-us/data/jj591620.aspx#ManyToMany