c# - 'System.String[]' 不能映射到原始类型
问题描述
我想将数组存储在数据库列中。
public string[] carList { get; set; }
但这给了我错误:
“SandStormAdmin.Models.PricePlan”类型上的属性“carList”具有无法映射到原始类型的属性类型“System.String[]”。
它只会在运行时给我这个错误,我正在使用 microsoft sql server 来存储数据。carList 数据类型存储在表中是 nvarchar(50)
我的模型课
public partial class PricePlan
{
public int PricePlanID { get; set; }
public int CarID { get; set; }
public string PricePlanName { get; set; }
public Nullable<System.DateTime> DateRangeFrom { get; set; }
public Nullable<System.DateTime> DateRangeTo { get; set; }
public string DayRangeFrom { get; set; }
public string DayRangeTo { get; set; }
public decimal Amount { get; set; }
public string[] carList { get; set; }
public virtual Car Car { get; set; }
}
创建.cshtml
<div class="form-group">
@Html.LabelFor(model => model.carList, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("carList", ViewBag.carlistname as SelectList, "Please Select Fruit name", new { @class = "form-control chosen-select", @multiple = "true" })
@Html.ValidationMessageFor(model => model.carList, "", new { @class = "text-danger" })
</div>
</div>
价格计划控制器
public ActionResult Create()
{
//var result = (from carID in db.Cars select carID).ToList();
//var getcarlist = db.Cars.ToList();
SelectList list = new SelectList(db.Cars, "CarID", "Make");
ViewBag.carlistname = list;
//ViewBag.CarID = new SelectList(db.Cars, "CarID", "Make");
return View();
}
// POST: PricePlans/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PricePlanID,CarID,PricePlanName,DateRangeFrom,DateRangeTo,DayRangeFrom,DayRangeTo,Amount,carList")] PricePlan pricePlan)
{
if (ModelState.IsValid)
{
db.PricePlans.Add(pricePlan);
db.SaveChanges();
return RedirectToAction("List");
}
ViewBag.CarID = new SelectList(db.Cars, "CarID", "Make", pricePlan.Car);
return View(pricePlan);
}
解决方案
我认为问题在于您正在尝试将可能包含多个值的字符串数组存储在数据库列中,该列只能包含一个值。
有两种方法可以解决这个问题。最简单的方法是在存储之前将数组序列化为单个值。以下代码段用于string.Join
创建以分号分隔的字符串,其中包含 中的所有值carList
:
var serialisedCarList = string.Join(";", carList);
另一种选择,我会说对于关系数据库来说更惯用,是为汽车值引入一个新表,并为它们提供一个外键以将它们链接到PricePlan
记录。PricePlan
这创建了从记录到记录的一对多关系Car
,有效地允许PricePlan
“包含”多个汽车值。
推荐阅读
- python - 如何创建一个继承父类的子类,以便使用 python 覆盖某些属性?
- php - 如何在另一个页面中显示每个提交的表单数据
- excel - 循环遍历工作簿中的形状并根据位置重命名
- bash - 用于向后排序字典的shell脚本?
- r - 在R中的数据框中选择行
- soql - 使用 SOQL 进行双重分组
- javascript - 来自 npm follow-redirects .wrap() 函数的 MaxListenersExceededWarning
- javascript - 如何根据Vue中给出的输入增加数量
- javascript - 在 HTML 中显示完整的 ArrayList
- android-studio - 如何仅在填充(或触摸)EditText 后显示我的 DrawableRight 图像?