我有一个技术人员存储库,返回8个结果。我想用这些结果实例化ViewModel属性。我怎样才能做到这一点?
public class TechnicianViewModel
{
public Guid ID { get; set; }
public string UserName { get; set; }
public string Bio { get; set; }
public string GenerateName()
{
string str = GenerateURL();
str = str + ".jpg";
return str;
}
public string GenerateURL()
{
string phrase = string.Format("{0}", UserName);
string str = phrase.ToLower();
str = Regex.Replace(str, @"\s", "-");
return str;
}
}
数据对象返回的值包含分组为技术人员模型的8个结果。
技术员模型看起来像这样。
public class Technician
{
[ScaffoldColumn(false)]
[Key]
public Guid UserId { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public bool Licensed { get; set; }
[Required]
public bool Insured { get; set; }
[Required]
public bool DrugTested { get; set; }
public string EducationalLevel { get; set; }
public string Specialities { get; set; }
public string Bio { get; set; }
[Required,Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }
public bool IsFormerTech { get; set; }
public DateTime ExperienceDate { get; set; }
public string MobilePhone { get; set; }
[Required]
public string Branch { get; set; }
public DateTime ApprenticeshipStatusDate { get; set; }
public string ActivityStatus { get; set; }
public string ReviewURL { get; set; }
编辑: -
我已将查询移出构造函数,现在我将尝试在控制器中访问它。
public class TechnicianController : Controller
{
private readonly AADataContext aADataContext;
private readonly UnitOfWork unitOfWork;
private readonly TechnicianViewModel TechnicianViewModel;
public TechnicianController(AADataContext context)
{
aADataContext = context;
unitOfWork = new UnitOfWork(aADataContext);
var data = unitOfWork.TechnicianRepository.GetAll().Where(c => c.Branch == "Calgary").Where(a => a.ActivityStatus == "Active");
}
答案 0 :(得分:-1)
我认为查询不属于视图模型。如果需要视图模型的集合,请将此查询移出构造函数。您可以在控制器操作中执行此操作。
public ActionResult GetTechnicians(string branch, string status)
{
var data = unitOfWork.TechnicianRepository.GetAll()
.Where(c => c.Branch == "Calgary")
.Where(a => a.ActivityStatus == "Active")
.Select(t => new TechnicianViewModel
{
Id = t.UserId,
UserName = t.UserName,
Bio = t.Bio
});
...
}
如果您有多个这样的问题,或者如果您发现自己重复此查询,请将其移至新班级。
public class TechnicianService
{
private AADataContext context;
public TechnicianService(AADataContext context)
{
this.context = context;
}
public IEnumerable<TechnicianViewModel> GetTechnicians(string branch, string status)
{
}
}