I'm following the Entity Framework documentation to add a list of string in my Sqlite database.
It works fine when i'm adding the first item.
But as soon as i try to add another item and SaveChanges() i get a exception:
SQLite Error 19: 'NOT NULL constraint failed: MyModels.Tags'
Here is the code, it mostly comes from the EF documentation page
namespace ArrayDatabaseTest.Models
{
public class MyDatabase : DbContext
{
private string DbPath { get; }
public MyDatabase()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Avalonia", "ArrayDatabaseTest");
DbPath = Path.Join(path, "MyDatabase.db");
Trace.WriteLine($"DbPath: {DbPath}");
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlite($"Data Source={DbPath}");
}
protected override void OnModelCreating( ModelBuilder modelBuilder )
{
modelBuilder.Entity<MyModel>()
.Property(e => e.Tags)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize<List<string>>(v, (JsonSerializerOptions)null),
new ValueComparer<ICollection<string>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => (ICollection<string>)c.ToList()));
}
public DbSet<MyModel> MyModels { get; set; }
}
public class MyModel
{
public long Id { get; set; }
public string Name { get; set; } = "";
public ICollection<string> Tags { get; set; }
}
}
// In my ViewModel the code to add a new item
public void AddToMyDatabase( string name )
{
MyDatabase.MyModels.Add(new MyModel
{
Name = name,
Tags = new List<string>()
});
MyDatabase.SaveChanges();
}
How can i fix this issue ?
Thanks in advance for your answer.