【问题标题】:MVC with properties not mapped to the database具有未映射到数据库的属性的 MVC
【发布时间】:2014-10-02 18:54:45
【问题描述】:

我正在创建一个包含下拉列表和其他一些将更新数据库的字段的视图。在模型中有映射到数据库的属性和一些用于下拉列表的属性。未映射的属性会引发异常。有没有一种好方法可以从映射中排除下拉列表属性?我尝试将它们放在模型中的一个单独的类中,但没有奏效。

型号:

[Table("cardata")]//Links the external table to this model object
public class Cardata
{
    //Maps to the database
    public int id { get; set; }
    public int dealerID { get; set; }
    public string model { get; set; }
    public int numCyl { get; set; }
    public double weight { get; set; }


    // UNMAPPED Used for a drop list of car names
    public string carModel { get; set; }

    public IEnumerable<SelectListItem> carList
    {
        get
        {
            cartableContext ctc = new cartableContext();

            IEnumerable<SelectListItem> retVal = ctc.cardata.GroupBy(c => c.model).Select(cl => cl.FirstOrDefault()).Select(cars => new SelectListItem { Value = cars.id.ToString(), Text = cars.model.ToString() });
            return retVal;
        }
        set { }
    }        
}

【问题讨论】:

  • 不好的做法(在属性中有数据库访问代码)!您应该创建一个视图模型,其中包含视图特定元素的属性,例如SelectLists。您可以使用automapper 等工具将数据模型属性映射到视图模型属性。或者,您可以将 SelectList 添加到 ViewBag。

标签: asp.net-mvc-4 model


【解决方案1】:

你能用 [NotMapped] 吗?

[NotMapped]
public string carModel { get; set; }

[NotMapped]
public IEnumerable<SelectListItem> carList{...}

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 2020-10-05
    • 2019-02-01
    • 2014-01-26
    相关资源
    最近更新 更多