我正在尝试理解所有这些 ViewModel 内容并以正确的方式做事。我有几个模型通过 Entity Framework 链接到 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;}
}
我有一个像这样的 View 模型:
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;}
}
我的 Controller 如下:
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
。当我尝试从 DbSet
制作 Html.DropDownList
时,我得到了一个包含正确数量项目的列表,但它们都说“mynamespace.Models.HardwareOption”。这是有道理的,我只是不知道如何正确地做到这一点。
最佳答案
你可以用 DbSet<T>
做的有用的事情在你的例子中是一个投影。您将定义第二个 ViewModel,其中包含要在下拉列表中显示的属性:
public class HardwareOptionViewModel
{
public int Id { get; set; }
public string Configuration { get; set; }
public string AnotherProperty { get; set; }
//...
}
而不是 DbSet
您正在 OrderIndexViewModel
中使用此 ViewModel 的集合:
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();
编辑
您可以将集合绑定(bind)到下拉列表,如下所示:
@model MyNamespace.OrderIndexViewModel
...
<div>
@Html.DropDownListFor(model => model.CurrentHardwareOptionId,
new SelectList(Model.HardwareOptions, "Id", "Configuration",
Model.CurrentHardwareOptionId))
</div>
这里我介绍了一个新属性CurrentHardwareOptionId
上OrderIndexViewModel
与 Id
具有相同的类型(本例中为 int
),这应该是所选 Id
的属性。下拉列表中的内容应该在页面回发时绑定(bind):
public class OrderIndexViewModel
{
//...
public int CurrentHardwareOptionId { get; set; }
}
关于c# - 例如,如何将 DbSet 变成下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12647079/