Entity Framework 1-n

0

I do not even know if I'm feeling what I'm trying to do.

If I try to add a Course to a Flag, fine. But when I try to add a list of Courses in a Flag, the following error occurs:

  

Additional information: An entity object can not be referenced by   multiple instances of IEntityChangeTracker.

Classes:

[Table("Area_Cursos_Bandeira")]
public class Bandeira
{
    public int BandeiraID { get; set; }
    public string Nome { get; set; }
    public string Logo { get; set; }
    public string Site { get; set; }
    public virtual ICollection<Curso> Cursos { get; set; }
}

[Table("Area_Cursos_Curso")]
public class Curso
{
    public int CursoID { get; set; }
    public int BandeiraID { get; set; }
    public virtual Bandeira Bandeira { get; set; }
    public string Nome { get; set; }
}

Repository

public IQueryable<TEntity> GetAll()
{
    return ctx.Set<TEntity>();
}

public void SalvarTodos()
{
    ctx.SaveChanges();
}

public void Adicionar(TEntity obj)
{
    ctx.Set<TEntity>().Add(obj);
}

Main

BancoContexto bc = new BancoContexto();
var bdBandeira = BandeiraAplicacaoConstrutor.BandeiraAplicacaoEF(bc);
var bdCurso = CursoAplicacaoConstrutor.CursoAplicacaoEF(bc);       
var todosCursos = bdCurso.GetAll().ToList();

var bandeiraADD = new Bandeira
{
    Logo = "logo",
    Nome = "nome",
    Site = "www.sdadas.com.bg",
    Cursos = todosCursos
 };

bdBandeira.Adicionar(bandeiraADD);
bdBandeira.SalvarTodos();
    
asked by anonymous 09.09.2014 / 20:57

1 answer

2

You are loading Flags and Courses in different contexts. For this to work, the Flags and Courses context needs to be the same.

I would do something like this:

var bdBandeira = BandeiraAplicacaoConstrutor.BandeiraAplicacaoEF(context);
var bdCurso = CursoAplicacaoConstrutor.CursoAplicacaoEF(context);    
    
09.09.2014 / 21:20