首页 > 解决方案 > '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);
        }

数据库表数据类型图片

[1]:https://i.stack.imgur.com/Y2U9U.png

标签: c#asp.net-mvc

解决方案


我认为问题在于您正在尝试将可能包含多个值的字符串数组存储在数据库列中,该列只能包含一个值。

有两种方法可以解决这个问题。最简单的方法是在存储之前将数组序列化为单个值。以下代码段用于string.Join创建以分号分隔的字符串,其中包含 中的所有值carList

var serialisedCarList = string.Join(";", carList);

另一种选择,我会说对于关系数据库来说更惯用,是为汽车值引入一个新表,并为它们提供一个外键以将它们链接到PricePlan记录。PricePlan这创建了从记录到记录的一对多关系Car,有效地允许PricePlan“包含”多个汽车值。


推荐阅读