create linked entities in EF based on automatically generated id

entity-framework entity-framework-6

Question

Challenge in EF6:

how to check Id of resulting row in the database after running this (esentially adding an entity record):

repository.Add(myEntity1);  

...and use that id to add the second entity which has property X = to the id of the first entity?

use that id to add the second entity which has property X = to the id of the first entity?

repository.Add(myEntity2);

Right now there is no linkage between entity 1 and entity 2 because i don;t know how to save the id (automatically generated by ef) after first add ... and preserve it for adding it as a fk in the second entity?

Thanks a lot

1
0
6/21/2018 10:14:04 AM

Popular Answer

You could try this following after your call to SaveChanges:

myEntity2.X = myEntity1.Id;

Then call SaveChanges again. This doesn't really utilise the power of Entity Framework, however, which is in managing relationships between entities. If your class was defined something like this:

public class MyEntity
{
    [Key]
    public int Id { get; set; }

    [ForeignKey(nameof(RelatedEntity))]
    public int RelatedEntityId { get; set; }
    public MyEntity RelatedEntity { get; set; }
}

You could add your entities something like the following, and the Id/foreign key matching would be handled for you after calling SaveChanges:

myEntity1.RelatedEntity = myEntity2;

This is a fairly general solution, so if you'd like something more specific then you will need to include more details in your question.

You can read more about configuring Entity Framework relationships here.

0
6/23/2018 4:26:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow