我在 C# 中使用 LINQ 时遇到问题,我不断收到“指定的转换无效”。这就是我想要做的。
我创建了一个类,我在其中声明了表的所有列。
[Table(Name="tbl_Aff")] public class Affiliate { [Column] public string name; [Column] public string firstname; [Column] public string surname; [Column] public string title; }
然后我声明一个强类型的 DataContext,在其中我将所有 Table 集合声明为上下文的成员。
public partial class Database : DataContext { public Table<Affiliate> affiliate; public Database() : base(Settings.getConnectionString()) { } //This method gets the connection string by reading from an XML file. }
public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Database database = new Database(); try { var q = from a in database.affiliate select a; foreach (var aff in q) // Here I get the error "Specified cast is not valid" { lblMessage.InnerHtml += aff.name + "
"; } } catch (Exception ex) { System.Console.WriteLine(ex.Message); } } }
最佳答案
GetInt32()
表明 tbl_Aff
的至少一列实际上不是字符串 ([n]varchar(...)
/[n]text
),你没有给它任何提示。这里最简单的技巧是简单地将该属性设置为 int
(因为这显然是它想要的)。
我还想知道您是否还没有展示更多Affiliate
;接口(interface)、基类、单独的部分类等(因为这些列看起来应该是字符串)。
这个问题困扰我的主要时间是当我(例如)在数据库中有一个tinyint
,并且忘记相应地键入一个枚举(:字节
在那个例)。
关于c# - C# 中的 LINQ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3021914/