Problem with LINQ in C#

David Bonnici Source

I am encountering a problem when using LINQ in C#, I am constantly getting "Specified cast is not valid". This is what I am trying to do.

I create a class in which I declare all the columns of the table.

    public class Affiliate 
        public string name;
        public string firstname;
        public string surname;
        public string title;

I then declare a strongly typed DataContext in which I declare all Table collections as members of the context.

    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();

                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 += + "
"; } } catch (Exception ex) { System.Console.WriteLine(ex.Message); } } }


answered 8 years ago Marc Gravell #1

The GetInt32() suggests that at least one of the columns of tbl_Aff is not actually a string ([n]varchar(...)/[n]text), and you haven't given it any hints. The simplest trick here is to simply hake that property an int (since that is what it clearly wants).

I'm also wondering if there is more to Affiliate that you haven't shown; interfaces, base-classes, a separate partial class etc (as those columns look like they should be strings).

The main time this problem bites me is when I have (for example) a tinyint in the DB, and forget to type an enum accordingly (: byte in that case).

comments powered by Disqus