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
Try to disable database generation of the key:
You seem to want to supply your
Versionvalues manually when you add a new entity to the database. By default, EF assumes the keys of typeintare 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 setDatabaseGeneratedOption.NoneEF will sent the value you set as the key to the database.