Format exception for LINQ to sql. String must be exactly one character long
This code throws an error "Format exception. String must be exactly one character long". I cant see why. Any ideas?
var contract = (from c in db.SM_CONTRACTs
where c.CON_TUK2 != null
&& c.CON_TUK2 == req.Imei
select c).FirstOrDefault();
req.Imei looks like "8944200005977030038"
The data context loooks like:
[Column(Storage="_CON_TUK2", DbType="VarChar(20)")]
public string CON_TUK2
{
get
{
return this._CON_TUK2;
}
set
{
if ((this._CON_TUK2 != value))
{
this.OnCON_TUK2Changing(value);
开发者_如何转开发 this.SendPropertyChanging();
this._CON_TUK2 = value;
this.SendPropertyChanged("CON_TUK2");
this.OnCON_TUK2Changed();
}
}
}
What is probably going on is that the SM_CONTRACTs table in your database has one or more varchar(1) (or nvarchar(1)) columns. The Code Generator will convert this to System.Char in your model. This will throw the FormatException whenever the data is not exactly one character.
Try to look for this column in your model designer and change the Code Generation - Type property to 'String'.
It has not necessarily to do with a field that you use in your specific linq query (or within your where
statement)!
It could be ANY of your models fields that is a CHAR(1)
but has an "empty string" as data stored. Which is valid for an sql CHAR
type, but not for System.Char
in C#.
Changing this fields type to string
should be the easy fix.
精彩评论