c# - C# 中的 LINQ 问题

标签 c# .net asp.net linq-to-sql

我在 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/

相关文章:

.net - 从现有的winforms应用程序中分离 View 层的路径?

c# - 有没有办法在 C# 中直接从磁盘填充和使用变量?

c# - 无法在 asp.net 报表查看器中查看 SQL Server 移动报表

javascript - 客户端加密 - 任何建议/最佳实践 - 指出正确的方向吗?

c# - 如何设置这个Stub对象的返回值?

c# - 为预处理器指令赋值

.net - StringCollection 还是对象容器?

c# - Azure网站IE10/11错误SCRIPT7002 : XMLHttpRequest: Network Error 0x2ef3,由于错误00002ef3而无法完成操作

c# - 加载其他语言的资源

C# 替代 n :m-relation 的枚举