在EF中选择外键数据

时间:2014-02-10 16:31:52

标签: linq entity-framework entity-framework-4

我有2个模型:帐户和任务

public class Account
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Key]
    public Guid UserId { get; set; } 
    public string UserType { get; set; }
    public string Name { get; set; }

}

public class Task
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    [Key]
    public Guid TaskId { get; set; }
    [ForeignKey("TaskSubType")]
    public Guid TaskSubTypeId { get; set; }
    public virtual TaskSubType TaskSubType { get; set; }
    [ForeignKey("Account")]
    public  Guid TaskCreator { get; set; }      
    public virtual Account Account { get; set; }
}  

我打电话给getTasks:

public List<TaskOverViewViewModel> GetTasks()
{

    IEnumerable<Task> result =  db.Tasks.AsEnumerable();

    List<TaskOverViewViewModel> list = ToViewModelMapper.toViewModel(result);

    return list;
}

 public class ToViewModelMapper
    {

       internal static List<TaskOverViewViewModel> toViewModel(IEnumerable<Task> entitys )
        {
            List<TaskOverViewViewModel> modelList = new List<TaskOverViewViewModel>();
            foreach (var entity in entitys)
            {
                TaskOverViewViewModel model = new TaskOverViewViewModel();

            model.SubTaskName = entity.TaskSubType.Name;
            model.TaskCreator = entity.Account.LoginName;
            model.ToolsAccesable = entity.ToolsAccesable;
            modelList.Add(model);

            }


            return modelList;
        }
    }

但它失败了,因为我的entity.TaskSubType和entity.Account为null。但是如果我在调用中返回IEnumerable<Task> result = db.Tasks.AsEnumerable();一切正常,我可以看到Json包含所有TaskSubtype和Account模型。

1 个答案:

答案 0 :(得分:1)

从linq到实体,您可以直接投影到ViewModel类。

public List<TaskOverViewViewModel> GetTasks()
{
  List<TaskOverViewViewModel> result =  (from t in db.Tasks
                                         select new TaskOverViewViewModel
                                         {
                                           SubTaskName = t.TaskSubType.Name;
                                           TaskCreator = t.Account.LoginName;
                                           ToolsAccesable = t.ToolsAccesable;
                                         }).ToList();
  return result;
}

如果您更喜欢方法语法,可以使用:

List<TaskOverViewViewModel> result =  db.Tasks.Select(t => new TaskOverViewViewModel
                                      {
                                        SubTaskName = t.TaskSubType.Name;
                                        TaskCreator = t.Account.LoginName;
                                        ToolsAccesable = t.ToolsAccesable;
                                      }).ToList();