Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Non Identity - Cannot insert the value NULL into column 'ID'

I have a table with a primary Key of ID, this field is not an identity column. My migration for Entity Framework 6 is

 CreateTable(
   "dbo.Action",
    c => new
    {
       ID = c.Int(nullable: false, identity: false),
       ActionName = c.String(maxLength: 50),
    })
    .PrimaryKey(t => t.ID);

This all looks fairly straight forward to me. Then I have a method to seed some data:

public static void Seed(this DbSet<Action> entitySet)
{
    MainContext dbCtx = DataRepositoryBase<Action>.GetContext(entitySet) as MainContext;
    if (dbCtx != null)
    {
            entitySet.Add(new Action()
            {
                ID = 1,
                ActionName = "Test"
            });                
    }
}

It's at the this point I get an error

"Cannot insert the value NULL into column 'ID', table 'dbo.Action'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated"

As you can see I am clearly providing an value for the ID column. My suspicion is that Entity Framework is expecting the ID to be an Identity column

The Entity class is very simple

[DataContract]
public class Action
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string ActionName { get; set; }
}
like image 861
keitn Avatar asked Nov 16 '15 14:11

keitn


2 Answers

Your migration only creates the table in the database but doesn't tell Entity Framework the the ID property is not an IDENTITY column. EF picks the property called ID if you do not tell it which property to use as the primary key, but you also need to tell EF that it's not an IDENTITY column, do this using the DatabaseGenerated attribute:

[DataContract]
public class Action
{
    [DataMember]
    [Key] //This isn't technically needed, but I prefer to be explicit.
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [DataMember]
    public string ActionName { get; set; }
}
like image 83
DavidG Avatar answered Nov 17 '22 20:11

DavidG


The error is due to the fact that fields name Id are supposed to be primary key and identity.
When EF generate insert statement does not generate value for that field.

You can fix it using

[DataContract]
public class Action
{
    [DataMember]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [DataMember]
    public string ActionName { get; set; }
}
like image 35
bubi Avatar answered Nov 17 '22 19:11

bubi