API获取时的Null List属性

时间:2016-11-28 11:15:21

标签: c# api get null

我想知道是否有人可以帮我弄清楚为什么我在API获取后获得null属性值。

使用训练模型

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; }
}

活动模型

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

起初我将活动放在使用模型中。 Put工作正常并且数据库中的记录添加但是当我调用Api get for usertraining时它返回json,其活动等于null。

1 个答案:

答案 0 :(得分:0)

正如DavidG在评论中已经提到的那样,您需要添加Include()来加载引用的列表。将您的GET方法更改为此类

// 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;
    }