I'm new to Entity Framework, and I'm trying to create a pair of entity classes that have a one-to-many relationship. The tutorials and articles I've found just tell you how to set up the two classes. I followed their instructions and have verified that the child objects do automatically set the foreign key to the parent key's value, which is right, and SaveChanges on the context works (or does not give an error). But when I do a get, the collection is null.
I think I'm missing something I need to do that the tutorials and articles take for granted. Do I need to do something in my get to ensure that the ICollection in my parent class gets filled?
Here's the Parent entity:
public class Character
{
[Key]
public string Id { get; private set; }
...
public virtual ICollection<Fault> Faults { get; set; }
}
And Here's my child:
public class Fault
{
[Key]
[DatabaseGenerated( DatabaseGeneratedOption.Identity )]
public string FaultId { get; set; }
public string FaultName { get; set; }
public string CharacterId { get; set; }
public virtual Character Character { get; set; }
}
In my context, I added:
public DbSet<Character> Characters { get; set; }
public DbSet<Fault> Faults { get; set; }
Is there anything else I need to do? The Post seems to succeed, but the get of Character doesn't give me a filled in collection for Faults. Do I have to manually query the Faults and build the collection?
If you say that the create works and you see it saved it your data file
Then when querying to get the data you need to include it
dataSource.Character.Include(x => x.Faults )
See this link https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.infrastructure.dbquery-1.include?view=entity-framework-6.2.0