praeclarum / sqlite-net

Simple, powerful, cross-platform SQLite client and ORM for .NET
MIT License
4.07k stars 1.42k forks source link

Default value not applying when recieve data from database #888

Open picolino opened 5 years ago

picolino commented 5 years ago

Database:

CREATE TABLE 'Table1' (
    'Id' integer not null primary key autoincrement,
    'SecondId' integer
)

Data:

insert into 'Table1' values (1, null)

C# code model:

public class Table1
{
    [SQLite.PrimaryKey]
    public int Id { get; set; }

    [DefaultValue(-1)]
    public int SecondId { get; set; } = -1;
}

Business logic:

var result = db.Table<Table1>().ToList().Single();
var secondId = result.SecondId // 0 value here

So the problem is null value in database realised as default(int) - zero (0) value in code. I expecting that default value will be as i mentioned in database model in c# code (-1).

p.s. I understand that better to use Nullable<int> type for SecondId property, but I also think that not applying default value defined in model makes little inconsistent behaviour.

picolino commented 5 years ago

Think this method is a place that must be modified for fix this behaviour.

Activator.CreateInstance (map.MappedType);

For fix require to retrieve default value from DefaultValueAttribute and then replace value of instance property by retrieved value from attribute.