Entity Framework 1-n

Asked

Viewed 83 times

0

I don’t even know if you’ve been feeling what I’m trying to do.

If I try to add a Course to a Flag, that’s fine. But when I try to add a Course list to a Flag, the following error occurs:

Additional information: An Entity Object cannot 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();

1 answer

2


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

I would do something like this:

var bdBandeira = BandeiraAplicacaoConstrutor.BandeiraAplicacaoEF(context);
var bdCurso = CursoAplicacaoConstrutor.CursoAplicacaoEF(context);    
  • But how could I pass the context? For the "main", has no knowledge of the context.

  • You would have to instantiate the context on Main.

  • It worked. But now from what I understand, there’s no point in me having my application layer anymore, because I’m instantiating the context. Right?

  • 2

    Right. Actually I’ve been trying to explain this to you for some time ;)

  • HAHAHAHAHA. Now it makes sense! Obg.

  • @Diegozanardo Did the answer solve the problem? If yes, you could mark it so your question becomes more "cute" (with a beautiful little green). If there’s still something missing, say I’m sure it’ll be answered.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.