This code is EntityFramework Code on .NET-8.
expt_table consists of a key and non-key column.
On an empty table, tried to do DbContext.Add of a single record.
namespace expt;
using NUnit.Framework;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("expt_table")]
[PrimaryKey(nameof(userName))]
public class DbPageCompleted {
[Column("user_name")]
[MaxLength(50)]
[Required]
public string? userName {get; set;}
[Column("last_update_time")]
[Required]
public DateTime? lastUpdateTime;
}
public class ExptContext : DbContext {
public DbSet<DbPageCompleted> pageCompletions { get; set; }
protected string connectionStr()
{
var connStr = Environment.GetEnvironmentVariable("SQLCONNSTR_DbConn");
if (connStr == null) throw new NoDbConnection();
return connStr;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string? connStr = connectionStr();
optionsBuilder.UseSqlServer(connStr);
}
public static ExptContext dbContext = new ExptContext();
}
[TestFixture]
public class ExptTests {
DbPageCompleted dbPageCompleted = new DbPageCompleted {
userName = "[email protected]",
lastUpdateTime = DateTime.Now.ToUniversalTime()
};
[Test]
public void Expt() {
ExptContext dbContext = ExptContext.dbContext;
dbContext.pageCompletions.Add(dbPageCompleted);
dbContext.SaveChanges();
}
}
gives an exception
----> Microsoft.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'last_update_time', table 'asubio1-db.dbo.expt_table'; column does not allow nulls. INSERT fails.
Have tried a few variants, but have not been able to get past this.
Is there something basic I am missing?