C#Linq to SQL无效的强制转换异常

时间:2014-01-13 02:15:46

标签: 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]
    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>();
    }

}

我的DataContext对象:

class DataManager : DataContext {

    public Table<Company> Companies {
        get {
            return this.GetTable<Company>();
        }
    }
//other tables emited
}

当我想要获得这些公司时(除了已删除的公司)我使用这个:

List<Company> comp = _db.Companies.Where(x => !x.Deleted).ToList();

_db是单独创建的,此时不是NULL。

我在“!x.Deleted”部分得到一个例外:“InvalidCastException:指定的强制转换无效。”

堆栈追踪:

   at System.Data.SqlClient.SqlBuffer.get_Boolean()
   at System.Data.SqlClient.SqlDataReader.GetBoolean(Int32 i)
   at Read_Company(ObjectMaterializer`1 )
   at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at GameShop.Form1.UpdateCompanyList() in c:\Users\Xpym\Documents\Visual Studio 2012\Projects\GameShop\GameShop\Form1.cs:line 117
   at GameShop.Form1..ctor() in c:\Users\Xpym\Documents\Visual Studio 2012\Projects\GameShop\GameShop\Form1.cs:line 20
   at GameShop.Program.Main() in c:\Users\Xpym\Documents\Visual Studio 2012\Projects\GameShop\GameShop\Program.cs:line 16
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

在数据库中(与对象相同),“已删除”字段不可为空。

此外,我可能还说我没有使用任何自动代码/表生成器(如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查询是奇怪的:

SELECT [t0].[Id], ... FROM [Companies] as [t0]

通常我会看到以下内容:

SLECT [t0].[Id] as [Id], ... FROM [Companies] as [t0]

也许这有助于找到解决方案。

1 个答案:

答案 0 :(得分:5)

您的DbMapping不正确。您需要将[dbo].[Companies].[Deleted]更改为bit或将Company.Deleted更改为字节。

ADO.Net将tinyint转换为System.Bytehttp://msdn.microsoft.com/en-us/library/cc716729%28v=vs.110%29.aspx)。

实际上,您正在尝试将该字节转换为bool。这是您的例外来源。