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.
[Table(Name="tbl_Aff")] public class Affiliate { [Column] public string name; [Column] public string firstname; [Column] public string surname; [Column] 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(); 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); } } }
Table<T>
is a generic class - but your code appears to be declaring a variable of typeTable
. What's the exact type ofaffiliate
? Also, what does the cast exception say in terms of what it's trying to cast from/to? – Jon Skeet1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader
2.MoveNext() at new_signup.Default.Page_Load(Object sender, EventArgs e) in C:\Users\m.buhagiar\Desktop\Signup_Solution\signupLogic\new_signup\Default.aspx.cs:line 28 – David Bonnici