How to insert Entities, related to other existing ones, into the Entityframework?

Asked

Viewed 290 times

4

In the case assuming an entity "Entidadea" that references an entity "Entidadeb", I want to save it, but referencing an entity B already existing ex:

EntidadeA a = new EntidadeA();
EntidadeB b = new EntidadeB();
b.Id = 5;// id de entidade existente no banco
a.EntidadeB = b;
context.EntidadesA.Add(a);
context.SaveChanges();
//porém neste caso o framework cria uma nova entidade para b,
//o real objetivo é referenciar uma entidade ja persistida com o id 5

2 answers

2

Do so

EntidadeA a = new EntidadeA();
EntidadeB b = new EntidadeB();
b.Id = 5;// id de entidade existente no banco
a.EntidadeB = b;

context.EntidadeB.Attach(a.EntidadeB);

context.EntidadesA.Add(a);
context.SaveChanges();
  • and if you have several related entities B, C, D,... you have some way to search for gifts without attacking them one by one, for example by tapping A directly ?

  • 1

    If you have several you will have to do a foreach(Entidadeb oEntidadeB in a.Entidadeb) { }

2


Alternatively, you can select all desired entities through a context and make the association. For example:

var minhasEntidades = contexto.EntidadesB.Where(e => e.Tipo == algumTipo).ToList();
var a = new EntidadeA {
    EntidadesB = minhasEntidades
};

contexto.EntidadesA.Add(a);
contexto.SaveChanges();

There are few situations where Attach is recommended, as for example if the record is certainly not mapped by the context at that time.

  • and in case I have n relations in Entidadea, as Entidadeb, C, D, E, ... and want to carry them without having to know them

  • What’s the difference between Where and Attach ? because simply setting the identity doesn’t work ?

  • 1

    Attach you are telling the context that the record already exists and that it, context, must accept that object as valid. I personally find this approach very dangerous. In the case of Where, you are actually making a selection in the database and asking the context to monitor the objects for you, so it’s a much safer approach.

  • Now, as for "don’t need to know the entities," I don’t understand why you need this.

Browser other questions tagged

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