Entity Framework Entity Framework update and delete

10

I have a student table that has many-to-many relationship with the course table. This results in the CursoAluno table.

I would like to know the correct way for update and delete of the CursoAluno table.

For example, when there is an update related to the AlunoXCurso relationship, do I need to delete all data related to that Student and add it all again or have a more correct way?     

asked by anonymous 06.05.2014 / 13:37

2 answers

9

This question in advance is conceptual and has no relation to the Entity Framework itself.

About your question, you should think of Aluno and Curso : courses exist without students and students there are no courses; a student belongs to a course, but a course belongs to your company.

In short, the best practice in my point of view is to create an interploration table, basically like CursoAluno you did, only more well-cut.

Let's think:

  • Can a student be in more than one course?
    • If so, then the nomenclature is wrong: CursosAluno would be the best case, after all, a student can belong to more than one course simultaneously.
      • Tables that interpellate should have their structure trivial and simple - this makes them flexible. Here is an example that I like and practice a lot, but that will probably require foreign keys for both columns, because if one or the other - student or course - cease to exist, the relationship - in principle - must be undone. Remembering that with this structure, the other tables are free to be modified because they do not directly affect their cultures, just as they interact with each other.
  

CoursesAlumni.sql

+----+----------+----------+
| id | aluno_id | curso_id |
+----+----------+----------+
| 1  | 1        | 1        |
+----+----------+----------+
| 2  | 1        | 2        |
+----+----------+----------+
    • If not, then you do not need this interlock table which is the current CursoAluno . The only thing required would be for you to put in the Alunos table a field called curso_id - so you'll be able to work with the desired flexibility.

Giving depth to your case, let's consider the following:

  

Courses.sql

+----+----------------+
| id | name           |
+----+----------------+
| 1  | C#             |
+----+----------------+
| 2  | PHP            |
+----+----------------+
| 3  | Banco de dados |
+----+----------------+
     

Students.sql

+----+----------------+
| id | name           |
+----+----------------+
| 1  | João           |
+----+----------------+

So let's consider that John is marred in C # and Database . Your CursosAluno table looks like this:

+----+----------+----------+
| id | aluno_id | curso_id |
+----+----------+----------+
| 1  | 1        | 1        |
+----+----------+----------+
| 2  | 1        | 3        |
+----+----------+----------+

Now, you want to reallocate it from C# to PHP , then we remove the line WHERE aluno_id = 1 AND curso_id = 1 and then add a new record to aluno_id = 1 and curso_id = 2 .

In this way, we will have the following result:

+----+----------+----------+
| id | aluno_id | curso_id |
+----+----------+----------+
| 1  | 1        | 2        |
+----+----------+----------+
| 2  | 1        | 3        |
+----+----------+----------+

If you stop to think, we have a unanimous, independent structure, easy maintenance and simple concept.

    
06.05.2014 / 15:29
9

Diagram of tables and their relationships (N-M)

EntitiesandDbContext

//RepresentaTabelaAluno[Table("Aluno")]
public class Aluno
{
    public Aluno()
    {
        this.Cursos = new HashSet<Curso>();
    }
    [Key()]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int AlunoId { get; set; }
    public String Nome { get; set; }
    public virtual ICollection<Curso> Cursos { get; set; }
}
//Representa Tabela Curso
[Table("Curso")]
public  class Curso {
    public Curso ()
    {
        this.Alunos = new HashSet<Aluno>();
    }

    [Key()]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int CursoId { get; set; }
    public String Descricao { get; set; }

    public virtual ICollection<Aluno> Alunos { get; set; }
}
//Representa o DbContext
public class Context: DbContext
{
    public Context()
        : base("Data Source=.\SqlExpress;Initial Catalog=BaseDados;Persist Security Info=True;User ID=sa;Password=senha") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {       
        modelBuilder.Entity<Curso>()
                .HasMany(a => a.Alunos)
                .WithMany(c => c.Cursos)
                .Map(x =>
                {
                    x.MapLeftKey("CursoId");
                    x.MapRightKey("AlunoId");
                    x.ToTable("CursoAluno");
                });

        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Curso> Curso { get; set; }
    public DbSet<Aluno> Aluno { get; set; }
}

Operations

Insert

In this procedure was inserted Course in the Course table, Student in the Student Table. After this the course was inserted into the Student Courses (in the relationship table N - M).

Context db = new Context();

//INSERINDO CURSO NA TABELA CURSO
Curso curso = new Curso();
curso.Descricao = "Informática Basica";

//INSERINDO ALUNO NA TABELA ALUNO
Aluno aluno = new Aluno();
aluno.Nome = "Aluno Nome 1";

//ADICIONANDO NO CONTEXTO
db.Curso.Add(curso);
db.Aluno.Add(aluno);

//INSERINDO CURSO PARA O ALUNO
aluno.Cursos.Add(curso);

//SALVANDO REALMENTE OS DADOS
db.SaveChanges();

Delete

This exclusion has a reference to the CourseAluno table where the Course that is within Students will be excluded. This course in the course table will normally exist, ie it was excluded from the relationship table and not from the main course table

Context db = new Context();
//EXCLUIR DO ALUNO 1 O CURSO 1
Aluno aluno = db.Aluno.Find(1);
Curso curso = aluno.Cursos.Where(x => x.CursoId == 1).FirstOrDefault();
if (curso != null)
{
    aluno.Cursos.Remove(curso);
}
//SALVANDO REALMENTE OS DADOS
db.SaveChanges();

When working with N-M relationships, we do the two Add and Remove operations, the updates are done directly in Student and Course since they have all the necessary fields.

Update

Context db = new Context();
Aluno aluno = db.Aluno.Find(1);
aluno.Nome = "Alterando o nome";

Curso curso = db.Curso.Find(1);
curso.Descricao = "Alterando Curso";

db.SaveChanges();

Note: In this section you can update the main data of Student and Courses and also work with Delete and Add in the relationship table.

Example

Context db = new Context();
Aluno aluno = db.Aluno.Find(1);
aluno.Nome = "Alterando o nome";

//Novo curso que vai ser adicionado na tabela de Curso e relacionamento para o Aluno existente
Curso curso = new Curso();
curso.Descricao = "C#";

aluno.Cursos.Add(curso);

db.SaveChanges();
    
06.05.2014 / 16:26