【发布时间】:2015-05-28 09:25:15
【问题描述】:
我有以下课程:
public class SectionViewModel
{
private static EFModels.VTSEntities _db = new EFModels.VTSEntities();
public int ID { get; set; }
public string SectionName { get; set; }
public bool Active { get; set; }
public string SiteName { get; set; }
}
我想从 _db.Sections 中选择一个元素并填充这个类的对象。我可以这样做:
public SectionViewModel(int ID)
{
var s = (from i in _db.Sections
where i.ID == ID
select new SectionViewModel()
{
ID = i.ID,
SectionName = i.SectionName,
Active = i.Active,
SiteName = i.Site.SiteName
}).FirstOrDefault();
ID = s.ID;
SectionName = s.SectionName;
Active = s.Active;
}
它可以工作,但是当字段数为 10 时,代码量很大。我想写一些类似的东西
// IT DOES NOT WORK, ONLY EXAMPLE
public SectionViewModel(int ID)
{
this = (from i in _db.Sections
where i.ID == ID
select new SectionViewModel()
{
ID = i.ID,
SectionName = i.SectionName,
Active = i.Active,
SiteName = i.Site.SiteName
}).FirstOrDefault();
}
添加:
创建 SectionViewModel 对象(它是一个视图模型类):
public ActionResult SectionForm(int? id)
{
SectionViewModel model = new SectionViewModel(id);
return View(model);
}
但是,当然,这是不可能的,因为“this”只能用于读取。有什么办法吗?
【问题讨论】:
-
@Gert Arnold,我已添加
-
如果我正确理解您的问题,这就是为什么存在像 Automapper 这样的产品的原因。
-
我建议您阅读有关如何使用 MVC + EF 的信息。你的代码是错误模式的密集集合,显然是受到过去编程传统的微弱回响的启发。回到绘图板。
-
我读过很多这样的文章。你能描述一下为什么我的方法是错误的吗?如果有必要,我只想在构造函数中填充我的 View 模型。哪种模式被打破了?
标签: asp.net-mvc architecture entity-framework-6