Krzysztof Kozieł Krzysztof Kozieł - 9 days ago 5
C# Question

Null List attribute when API get

I was wondering if anyone could help me figure out why I'm getting null attribute value after API get.

Usertraining model

public class UserTraining
{
public int UserTrainingId { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public int TrainingId { get; set; }
public virtual Training Training { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Date { get; set; }
//Value2 is time in min
public double Value2 { get; set; }
public int BurnedCalories { get; set; }
public int AvgHR { get { if (SessionTraining.Count > 0) { return Convert.ToInt32(SessionTraining.Average(s => s.HeartRate)); } else return 0; } }
public virtual ICollection<SessionTraining> SessionTraining { get; set; }
//public virtual ICollection<Activity> Activities { get; set; }
public List<Activity> Activities { get; set; }
}


Activity model

public class Activity
{
[Key, Column(Order = 0)]
public int UserTrainingId { get; set; }
public Movement Movement { get; set; }
[Key, Column(Order = 1)]
public DateTime StartTime { get; set; }
public DateTime StopTime { get; set; }
public int AvgHR { get; set; }
public int BurnedKcal { get; set; }
public virtual UserTraining UserTraining { get; set; }


public Activity(DateTime start, Movement movement, DateTime stop)
{
StartTime = start;
Movement = movement;
StopTime = stop;
}

}
public enum Movement
{
Layover,
Walk,
Run
}


PUT for activities

[HttpPut]
[Route("api/usertraining2/addactivity/{id}")]
public IHttpActionResult AddActivity(int id)
{

var usertraining = db.UserTrainings.Where(u => u.UserTrainingId == id).SingleOrDefault();
var sessionsTraining = db.SessionTrainings.Where(u => u.UserTrainingId == id).ToList();
List<Activity> activities = ActivityManager.analizeActivity(sessionsTraining);
usertraining.Activities = activities;

db.SaveChanges();

return Ok(usertraining);
}


get

// GET: api/UserTraining1
public IEnumerable<UserTraining> GetUserTrainings()
{
var userid = User.Identity.GetUserId();
var usertrainings = db.Set<UserTraining>().Where(u => u.UserId == userid).ToArray();
return usertrainings;
}


At first I'm putting activity in usertraining model. Put works fine and records in database adds but when i call Api get for usertraining it returns json with Activity equal null.

Answer

As DavidG already mentioned in the comments, you need to add Include() to load the referenced list. Change your GET method to something like this

// GET: api/UserTraining1
    public IEnumerable<UserTraining> GetUserTrainings()
    {
        var userid = User.Identity.GetUserId();
        var usertrainings = db.Set<UserTraining>().Where(u => u.UserId == userid).Include(u=>u.Activities).ToArray();
        return usertrainings;
    }