I have two models Garden and Flower
public class Garden
{
public int Id { get; set; }
public string Name { get; set; } // Default value: Garden #[Id]
// Location.
public int LocationX { get; set; }
public int LocationY { get; set; }
// Flowers.
public virtual List<Flower> Flowers { get; set; }
}
public class Flower
{
public int Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public double Height { get; set; }
public DateTime LastWatered { get; set; }
public DateTime Planted { get; set; }
}
public class DataContext : DbContext
{
public DbSet<Garden> Gardens { get; set; }
}
And now, I need to select a flower by Id. I got to this, but I’m not sure that’s the good way. How should I do it? Do you have any articles about that?
var garden = _db.Gardens.Where(g => g.Id == gardenId).SingleOrDefault();
var flower = garden.Flowers.Where(f => f.Id == flowerId).SingleOrDefault();
I would suggest this:
Instead of using Where first and SingleOrDefault afterwards just use SingleOrDefault.
EDIT
As @JoachimIsaksson suggested, I have added a null reference check for garden to avoid the possible NullReferenceException.