[英]How to turn a DbSet into a dropdown list, for example?
我试图将所有ViewModel的东西都包裹起来,并以正确的方式进行操作。 我有几种通过实体框架链接到SQL表的模型,如下所示:
[Table("HardwareOptions", Schema = "dbo")]
public class HardwareOption {
[Key]
public int RecordID {get; set;}
[ForeignKey("Configuration")]
public string Configuration {get; set;}
public string ComputerManufacturer {get; set;}
public string ComputerModel {get; set;}
public string ComputerDescription {get; set;}
public int MonitorCount {get; set;}
public string MonitorManufacturer {get; set;}
public string MonitorModel {get; set;}
public string MonitorDescription {get; set;}
}
我有一个这样的视图模型:
public class OrderIndexViewModel {
public Customer Customer {get; set;}
public MetaUser MetaUser {get; set;}
public DbSet<HardwareOption> HardwareOptions {get; set;}
public DbSet<Machine> Machines {get; set;}
public DbSet<PendingOrder> PendingOrders {get; set;}
}
还有一点我的控制器是这样的:
private MyDbContext db = new MyDbContext();
OrderIndexViewModel viewmodel = new OrderIndexViewModel();
viewmodel.Customer = db.Customers.Find("myselffortesting");
viewmodel.MetaUser = db.MetaUsers.Find("myselffortesting");
viewmodel.HardwareOptions = db.HardwareOptions;
viewmodel.Machines = db.Machines;
viewmodel.PendingOrders = db.PendingOrders;
return View(viewmodel);
如您所见,在我看来,我只需要有关一个客户/用户的信息,但是我需要能够查询整个HardwareOptions,Machines和PendingOrders表。 现在,如果我的体系结构是完全错误的,请告诉我,因为更多的是这个问题的含义。 但是对于某些特定的东西,说我想从HardwareOptions中创建一个下拉列表。 从技术上讲,我希望每个SelectItem
都说几个列的值的字符串组合,但是现在我要说的是我只想要一个,如Configuration。 什么是正确的方法? 我不知道如何操作DbSet
。 当我试图做一个Html.DropDownList
从DbSet
,我得到了正确数量的项目列表,但他们都表示“mynamespace.Models.HardwareOption。” 这很有意义,我只是想不出正确的方法。
您可以在示例中使用DbSet<T>
进行的有用操作是projection 。 您将定义第二个ViewModel,其中包含要在下拉列表中显示的属性:
public class HardwareOptionViewModel
{
public int Id { get; set; }
public string Configuration { get; set; }
public string AnotherProperty { get; set; }
//...
}
您在DbSet
中使用的是此ViewModel的集合,而不是OrderIndexViewModel
:
public class OrderIndexViewModel
{
//...
public IEnumerable<HardwareOptionViewModel> HardwareOptions { get; set; }
//...
}
并且仅使用Select
方法从数据库中加载这些属性:
viewmodel.HardwareOptions = db.HardwareOptions
.Select(h => new HardwareOptionViewModel
{
Id = h.Id,
Configuration = h.Configuration,
AnotherProperty = h.AnotherProperty,
//...
})
.ToList();
编辑
您可以将集合绑定到一个下拉列表,如下所示:
@model MyNamespace.OrderIndexViewModel
...
<div>
@Html.DropDownListFor(model => model.CurrentHardwareOptionId,
new SelectList(Model.HardwareOptions, "Id", "Configuration",
Model.CurrentHardwareOptionId))
</div>
在这里,我在OrderIndexViewModel
上引入了一个新属性CurrentHardwareOptionId
,该属性具有与Id
相同的类型(在示例中为int
),并且应该是发布页面时下拉列表中所选Id
应该绑定到的属性。背部:
public class OrderIndexViewModel
{
//...
public int CurrentHardwareOptionId { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.