How to set a default value for a column in SQLite using SQLite-net?

3.3k views Asked by At

I'm importing an Android code to windows rt and I need the data to be compatible on both apps. When creating my sqlite database I need to set a default value to a column, doing something like

CREATE TABLE [blabla] ( [id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, [bleh] INTEGER NOT NULL DEFAULT -1 )

I wrote my C# code, using SQLite-net this way:

[Table("blabla")]
public class Blabla {
    [PrimaryKey, AutoIncrement, NotNull]
    public int id { get; set; }

    [NotNull]
    public int bleh { get; set; }
}

But I can't set the default value to 'bleh'. I need both database to be the same =/ Can anyone help me with this?

Thanks =)

3

There are 3 answers

0
Massita On BEST ANSWER

As long as didn't get an answer, I just created the whole database using the SQL statements, so the database won't need to be created by my C# code. It's working ok!

2
JKennedy On

Why don't you use:

    private int _bleh = 1;
    [NotNull]
    public int Bleh
    {
        get { return _bleh; }
        set { _bleh = value; }
    }

Then bleh will always have a default of 1 unless changed

0
bhavya joshi On

I know it's late but maybe this will help someone like me. If Default is supported by your SQLite, then use Default attribute

[Table("blabla")]
public class Blabla {
    [PrimaryKey, AutoIncrement, NotNull]
    public int id { get; set; }

    [NotNull,Default(value:1)]
    public int bleh { get; set; }
}

If Default is not supported by your SQLite,you can simply assign default value like this:

 [Table("blabla")]
    public class Blabla {
        [PrimaryKey, AutoIncrement, NotNull]
        public int id { get; set; }

        [NotNull]
        public int bleh { get; set; } = 1;
    }

I prefer second way always.