To reduce this problem to a simple version, I've created this table:
create table TestTable(id int primary key, descr varchar(50))
Note that the id
field is not an identity field. Now, if I try to use EF Code First to insert a row:
[Table("TestTable")]
public class TestTable
{
[Key]
public int id { get; set; }
public string descr { get; set; }
}
public class TestContext : DbContext
{
public TestContext(string connectionString) : base(connectionString) {}
public DbSet<TestTable> TestTables { get; set; }
}
static void Main()
{
const string connectionString = "...";
using (var db = new TestContext(connectionString))
{
db.TestTables.Add(new TestTable { id = 42, descr = "hallo" });
db.SaveChanges();
}
}
The result is an exception:
Cannot insert the value NULL into column 'id', table 'TestTable'; column does not allow nulls.
But the code that inserts the row specifies id = 42
. Any clue or hint welcome.
Just add this DataAnnotations [DatabaseGenerated(DatabaseGeneratedOption.None)]
and the libraries
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("TestTable")]
public class TestTable
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int id { get; set; }
public string descr { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With