create linked entities in EF based on automatically generated id

entity-framework entity-framework-6

Question

EF6 challenge:

How to verify the database row's ID when this is executed (basically creating an entity record):

repository.Add(myEntity1);  

...and add the second entity, which has the attribute X =, using that id to the id of the first object?

add the second entity, which contains the attribute X =, to the first entity's id using that ID?

repository.Add(myEntity2);

Due to my ignorance of how to keep the id (automatically created by ef) after the first addition and maintain it for adding it as a fk in the second entity, there is now no connection between entities 1 and 2?

Many thanks

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

Popular Answer

As a possible follow-up to your call toSaveChanges :

myEntity2.X = myEntity1.Id;

make a callSaveChanges again. The strength of Entity Framework, which is in managing interactions between entities, is not effectively used in this. If your class was described as follows:

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

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

The Id/foreign key matching would be taken care of for you after calling if you added your entities as follows:SaveChanges :

myEntity1.RelatedEntity = myEntity2;

If you require a more particular answer, you will need to include additional information in your query since this is a rather generic response.

More information on setting up Entity Framework relationships can be found in 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