C#Linq到SQL无效强制转换异常
所以我使用DataContext作为到DB的连接。我想从DB得到所有的公司,除了被删除的公司。 我的公司目标:C#Linq到SQL无效强制转换异常,c#,sql,linq,.net,C#,Sql,Linq,.net,所以我使用DataContext作为到DB的连接。我想从DB得到所有的公司,除了被删除的公司。 我的公司目标: [Table(Name = "Companies")] class Company { [Column(IsPrimaryKey = true, IsDbGenerated = true)] public int Id { get; set; } [Column] public bool Deleted { get; set; } [Column
[Table(Name = "Companies")]
class Company {
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int Id { get; set; }
[Column]
public bool Deleted { get; set; }
[Column]
public DateTime DateCreated { get; set; }
[Column]
public DateTime? DateModified { get; set; }
[Column]
public string Name { get; set; }
private EntitySet<Platform> _Platforms;
[Association(Storage = "_Platforms", OtherKey = "CompanyId")]
public virtual EntitySet<Platform> Platforms {
get {
return this._Platforms;
}
set {
this._Platforms.Assign(value);
}
}
public Company() {
this._Platforms = new EntitySet<Platform>();
}
}
在数据库中(与对象中相同),删除字段不可为空
此外,我还可以说,我没有使用任何自动代码/表生成器(如EF)
请帮助我解决这个问题,因为我自己找不到解决办法
更新
在另一种方法中,我使用以下代码,它执行时没有任何问题:
_db.Companies.Any(x=>!x.Deleted && x.Name == textBoxCompanyName.Text)
更新
SQL中的表是这样创建的:
CREATE TABLE [dbo].[Companies](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Deleted] [tinyint] NOT NULL,
[DateCreated] [datetime] NOT NULL,
[DateModified] [datetime] NULL,
[Name] [varchar](50) NOT NULL)
另外,在调试时,我注意到LINQ创建的SQL queryes很奇怪:
SELECT [t0].[Id], ... FROM [Companies] as [t0]
通常我会看到:
SLECT [t0].[Id] as [Id], ... FROM [Companies] as [t0]
这可能有助于找到解决方案。您的DbMapping不正确。您需要将
[dbo].[companys].[Deleted]
更改为bit
或将Company.Deleted
更改为byte
ADO.Net将tinyint
转换为System.Byte
()
实际上,您正在尝试将该字节直接强制转换为bool。这就是异常的来源。数据库中“已删除”字段是如何定义的?它有可能为空吗?您是否尝试将值作为
string
而不是bool
获取,并检查一次可能导致错误的值?请尝试List comp=\u db.companys.Where(x=>(x.Deleted!=null&&!x.Deleted)).ToList()代码>请包括您的表格定义好吗?此外,如果包含dbml文件,可能会有所帮助。看起来映射到属性的列之间不匹配。很可能它被映射到一个int或一些愚蠢的东西。查看堆栈跟踪很容易看出SQL已生成、运行,并且映射到实体类失败。@Damith已尝试:相同error@XpyM能否将[tinyint]
列更改为[bit]
?
CREATE TABLE [dbo].[Companies](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Deleted] [tinyint] NOT NULL,
[DateCreated] [datetime] NOT NULL,
[DateModified] [datetime] NULL,
[Name] [varchar](50) NOT NULL)
SELECT [t0].[Id], ... FROM [Companies] as [t0]
SLECT [t0].[Id] as [Id], ... FROM [Companies] as [t0]