尝试从MVC / Linq读取现有数据库时出错

时间:2014-01-09 14:44:30

标签: asp.net-mvc asp.net-mvc-3 linq entity-framework-4

我继承了一个数据库,我需要查询它。

但是当我在下面运行我的代码时,我收到错误:

{"The 'solution' property on 'QA' could not be set to a 'System.Byte' value. You must set this property to a non-null value of type 'System.Int32'. "}

表定义是:

CREATE TABLE [dbo].[qa](
[id] [int] IDENTITY(1,1) NOT NULL,
[r3_3] [tinyint] NULL,
[r6_3] [tinyint] NULL,
[r6_13] [tinyint] NULL,
[datesaved] [datetime] NULL
CONSTRAINT [PK_qa] PRIMARY KEY CLUSTERED 
(
[id] ASC
) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,            ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

所以r3_3,r_3,r6_13可以包含1,0或null。

我的控制器是:

    // GET: /QA/
    public ActionResult Index()
    {
        var qas = db.QAs;
        return View(qas.ToList());
    }

型号:

public class QA
{
    public int Id { get; set; }
    public DateTime date { get; set; }
    // solution
    [Column("r3_3")]
    public Int32? solution { get; set; }
    // priority
    [Column("r6_3")]
    public Int32? priority { get; set; }
    // assignment
    [Column("r6_13")]
    public Int32? assignment { get; set; }
}

鉴于我无法更改数据库,如何更改模型或控制器,以便能够撤回此表中的数据?

谢谢Mark,

1 个答案:

答案 0 :(得分:5)

应将tynint映射到.net字节,如msdn

中所述

所以你应该

[Column("r3_3")]
public byte? solution { get; set; }

如果你想使用另一个int?属性(不在db中),你可以添加

   [NotMapped]
   public int? IntSolution {
        get {return solution.HasValue (int?)Convert.ToInt32(solution.Value) : null;}
        set { solution = value.HasValue ? (byte?)Convert.ToByte(value.Value) : null;
        }
   }
相关问题