I have an some classes in C#, using a Database Context what would be the best way to load a class that in essence references/contains other classes?
Consider the following:
public class SomeClass
{
[Key]
[Column("id")]
public int Id { get; set; }
[ForeignKey("AnotherClass")]
[Column("anotherClassId")]
public int AnotherClassId { get; set; }
[ForeignKey("SomeOtherClass")]
[Column("someOtherClassId")]
public int SomeOtherClassId { get; set; }
[NotMapped]
public AnotherClass AnotherClass { get; set; }
[NotMapped]
public SomeOtherClass SomeOtherClass { get; set; }
}
public class AnotherClass
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("name")]
public string Name { get; set; }
}
public class SomeOtherClass
{
[Key]
[Column("id")]
public int Id { get; set; }
[Column("name")]
public string Name { get; set; }
}
public async Task<SomeClass> GetSomeClass(int id)
{
SomeClass someClass = null;
using (var db = new Database.Context())
{
someClass = await db.SomeClass.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id);
}
return someClass;
}
This is pretty much where I'd use a Join, and in any other language where I just use straight SQL that's what i would have done.
I could use additional queries afterwards, like so:
someClass = await db.SomeClass.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id);
someClass.AnotherClass = await db.AnotherClass.AsNoTracking().FirstOrDefaultAsync(a => a.Id == someClass.AnotherClassId);
someClass.SomeOtherClass = await db.SomeOtherClass.AsNoTracking().FirstOrDefaultAsync(s => s.Id == someClass.SomeOtherClassId);
But I'm certain that's incorrect.