Mark
Mark

Reputation: 7818

Error when trying to read an existing database from MVC/Linq

I've inherited a database, which I need to query against.

However when I run my code below, I get the error:

{"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'. "}

The table definition is:

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]

So r3_3, r_3, r6_13 can contain 1, 0 or a null.

My controller is:

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

Model:

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; }
}

Given I can't change the database, how can I change my model or my controller, to be able to pull back the data in this table?

Thank you, Mark

Upvotes: 1

Views: 2466

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

A tynint should be mapped to a .net byte, as stated in msdn

So you should have

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

If you want to work with another int? property (which wouldn't be in db), you could add

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

Upvotes: 5

Related Questions