简体   繁体   中英

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

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 =)

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM