EntityFramework 6: Doubt when Persisting a Relationship N for N

0

Template:

public class Agenda
{
    public int Id { set; get; }
    public string Horario { set; get; }
    public string Local { set; get; }
    public virtual IEnumerable<Exame> Exames { set; get; }
}

public class Exame
{
    public int Id { set; get; }
    public string Descricao { set; get; }
    public virtual IEnumerable<Agenda> Agendas { set; get; }
}

Entity Settings:

public class AgendaMap : EntityTypeConfiguration<Agenda>
{
    public AgendaMap()
    {
        HasMany(x => x.Exames)
                .WithMany(x => x.Agendas)
                .Map(x => x.ToTable("AgendaExame"));
    }
}

public class ExameMap : EntityTypeConfiguration<Exame>
{
    public ExameMap()
    {
    }
}

Repository Method:

public void Inserir(T obj)
{
    banco.Set<T>().Add(obj);
    banco.SaveChanges();
}

I can not find a solution to persist Agenda, as the bank generated the following tables (as I wanted it to):

Schedule (Id, Schedule, Location), Exam (Id, Description), and ScheduleExame (Id Schedule, Id_Exam)

And, with that, I need to get the Id, Time and Location properties from the Phonebook and save them in the Phonebook table. Then I get the Id of each Exam and also the Agenda Id and save it to the AgendaExame table. I do not even know where I'm going ...

Any tips? Thanks!

    
asked by anonymous 28.07.2016 / 20:50

1 answer

2

First, in your classes you must use ICollection in navigation properties. With IEnumerable you will not be able to modify.

No mapping:

public class AgendaMap : EntityTypeConfiguration<Agenda>
{
    public AgendaMap()
    {
        HasMany(x => x.Exames).WithMany(x => x.Agendas).Map(x => 
        {
            x.MapLeftKey("Agenda_Id");
            x.MapRightKey("Exame_Id");
            x.ToTable("AgendaExame"));
        }
    }
}

public class ExameMap : EntityTypeConfiguration<Exame>
{
    public ExameMap()
    {
        HasMany(x => x.Agendas).WithMany(x => x.Exames).Map(x => 
        {
            x.MapLeftKey("Exame_Id");
            x.MapRightKey("Agenda_Id");
            x.ToTable("AgendaExame"));
        }
    }
}

When creating or modifying, you do not have to worry about the ScheduleExame table. It only exists for the application. You will only manipulate the collections.

That is, if you add an object like this:

var agenda = new Agenda()
{
    Horario = "12:00",
    Local = "São Paulo"
    new List<Exame>
    {
        Descricao = "alguma coisa"
    }
};

It's already popular with all three tables.

Or to update existing objects:

var agendaJaExistente = this.SingleOrDefault(a => a.Id == id);
var novoExame = new Exame()
{
    Descricao = "alguma coisa",
    Agendas.Add(agendaJaExistente);
};
    
29.07.2016 / 16:00