Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First: Add row to table with a non-identity primary key

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.

like image 498
Andomar Avatar asked Jan 09 '14 14:01

Andomar


1 Answers

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; }
}
like image 164
Guillermo Oramas R. Avatar answered Oct 01 '22 07:10

Guillermo Oramas R.