Linq To Sql:异常“字符串必须正好一个字符长" [英] Linq To Sql: Exception "String must be exactly one character long"

查看:82
本文介绍了Linq To Sql:异常“字符串必须正好一个字符长"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个用varchar(1) NULL字段定义的SQL Server表.它用于存储性别字符.有些行包含数据,有些则没有:null或为空.授予空白应该为空,但在此认为空白是有效值.我更希望该值为null.

ID    Gender
1      'M'
4      'M'
3      ''
4      'F'

在运行someID的值为3的Linq To Sql查询时引发异常.

var emp = (from e in db.Employees
           where e.ID == someID
           select e);

例外:

字符串必须恰好是一个字符长.

问题:此异常的原因是什么?可以采取什么措施来预防或消除此问题?

解决方案

检查LINQ to SQL设计器为您创建的Employee类型. Gender属性的类型很可能是System.Char(这是LINQ to SQL设计器用于varchar(1)的类型),应更改为System.String以正确匹配您的数据库模式.

考虑到这是有效的T-SQL,LINQ to SQL设计器将varchar(1)解释为System.Char的事实是愚蠢的:

declare @foo varchar(1);
set @foo = '';

这是无效 C#:

Char foo = '';

由于生成的属性的类型限制太多,因此需要将其更改为System.String.

注意: 您可能要考虑在属性的设置器中添加一些验证,以在字符串的长度大于1时引发异常.

Consider a SQL Server table defined with a varchar(1) NULL field. It's being used to store a gender character. Some rows have data, some not: either null or blank. Granted the blanks SHOULD be nulls, but consider that blank is a valid value here. I'd much prefer the value to be null.

ID    Gender
1      'M'
4      'M'
3      ''
4      'F'

An exception is raised when running a Linq To Sql query where the value of someID is 3.

var emp = (from e in db.Employees
           where e.ID == someID
           select e);

Exception:

String must be exactly one character long.

Question: What is the cause of this exception? What can be done to prevent or eliminate this problem?

解决方案

Check the Employee type that was created for you by the LINQ to SQL designer. Most likely the type for the Gender property is System.Char (which is the type that the LINQ to SQL designer uses for varchar(1)) and should be changed to a System.String to properly match your database schema.

The fact that the LINQ to SQL designer interprets a varchar(1) as a System.Char is foolish considering that this is valid T-SQL:

declare @foo varchar(1);
set @foo = '';

and this is invalid C#:

Char foo = '';

Since the type of the property that was generated is too restrictive you need to change it to be a System.String.

Note: You may want to consider adding some validation inside the setter of the property to throw an exception if the length of the string is greater than one.

这篇关于Linq To Sql:异常“字符串必须正好一个字符长"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆