Artur Keyan
Artur Keyan

Reputation: 7683

NULL Exception in EF 4.1

I use Entity Framework 4.1, SQL Server 2008 & .NET 4.0
I have a Sql table:

create table SchemaVersion (
   Version              int                  not null,
   constraint PK_SCHEMAVERSION primary key (Version)
)

And POCO

    [Table("SchemaVersion")]
    public class SchemaVersion
    {
        [Key]
        public Int32 Version { get; set; }
    }

I added the column in table

     Context ctx = new Context();
     ctx.SchemaVersions.Add(new SchemaVersion() { Version = 2 });
     ctx.SaveChanges();

after i get the exception :

Cannot insert the value NULL into column 'Version', table 'Simply.dbo.SchemaVersion'; column does not allow nulls. INSERT fails. The statement has been terminated.

Context setup:

public class Context : DbContext
{
    public DbSet<SchemaVersion> SchemaVersions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        this.Configuration.ValidateOnSaveEnabled = false;
        base.OnModelCreating(modelBuilder);
    }
}

I think it is very strange, Who can help me solve this issue

Upvotes: 0

Views: 92

Answers (1)

Slauma
Slauma

Reputation: 177133

Try to disable database generation of the key:

[Table("SchemaVersion")]
public class SchemaVersion
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Int32 Version { get; set; }
}

You seem to want to supply your Version values manually when you add a new entity to the database. By default, EF assumes the keys of type int are identities in the database and will be generated there. Therefore EF would not send a value to the database. If the key is NOT an identity in the DB then no value for the key will be supplied at all, resulting in the exception. If you set DatabaseGeneratedOption.None EF will sent the value you set as the key to the database.

Upvotes: 4

Related Questions