Search code examples
c#windows-phonesql-server-ce

Windows Phone 8 existing database InvalidCastException: Specified cast is not valid


I am using pre populated database. When the app starts I copy the db from assets to the isostore. The Entity:

[Table(Name = "NAMES")]
public class NameItem: INotifyPropertyChanged,
INotifyPropertyChanging {
    public event PropertyChangedEventHandler PropertyChanged;
    public event PropertyChangingEventHandler PropertyChanging;

    private string _nameString;
    private int _id;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Name = "_id")]
    public int NameId {
        get {
            return _id;
        }
        set {
            if (value != _id) {
                OnPropertyChanging("NameId");
                _id = value;
                OnPropertyChanged("NameId");
            }
        }
    }

    [Column(IsPrimaryKey = false, Name = "NAME_TEXT")]
    public String NameString {
        get {
            return _nameString;
        }

        set {
            if (_nameString != value) {
                OnPropertyChanging("NameString");
                _nameString = value;
                OnPropertyChanged("NameString");
            }
        }
    }
}

And here I try to read data from db:

using(var db = new MyDataContext("isostore:/Database/ff.sdf")) {
    var allNameItems = db.NameItems.ToArray(); // exception on this line
    try {
        MessageBox.Show(allNameItems[0].NameString);
    } catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }
}

With this code I get InvalidCastException, but db.NameItems.Count() works.


Solution

  • Ok I read this question and found the problem, my id field in db was BigInt and in Entity it was int. I changed it to long and it worked.