Entity Framework 6 Guid as Primary Key: Cannot Insert the Value Null into Column 'Id', Table 'Filestore'; Column Does Not Allow Nulls

Code first from Database - Cannot insert the value NULL into column 'Id' but value actually is not null

You have specified DatabaseGeneratedOption.None

This means that EF is not expecting the database to generate the Id field, and that you should specify the Id field yourself.

If you want the database to generate the Id field automatically, then alter the column to be an IDENTITY type, and change the code to DatabaseGeneratedOption.Identity

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

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; }
}

C# and EF cannot insert NULL to Id column

Try to add DatabaseGeneratedOption.None annotation

public class MasterReview
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
}

or if you use FluentAPI

modelBuilder.Entity<MasterReview>().Property(t => t.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

DatabaseGeneratedOption.None option specifies that the value of a property will not be generated by the underlying database. So, use it if you want to provide your own values to id properties instead of database generated values

But note: EF will throw an exception if you do not provide unique values each time when Id is a primary key property.

Why it is trying to insert NULL in primary key property id.. MVC5 EF6

When I deployed the application I copied the database to the server. On the server the Id column was not set to primary key and it was not an identity column either. I think something went wrong while copying the database to the server. That's why it was throwing the exception.

EF Core - column does not allow nulls. INSERT fails

Turns out that the migrations that I ran did not run properly. The DefaultValue constraint was not applied against the column on the database.

Thanks everyone.

Solution:

  • Check the structure of your table and ensure that the fluent configuration and the database are in sync.

EFCore Cannot insert the value NULL into column

Your problem is here:

    public async Task<string> UpdateUs(User u)
{
_dbCont.Update(u);
await _dbCont.SaveChangesAsync();
return "ok";
}

I assume that your call-site for UpdateUs looks like this:

User u = new User()
{
Id = 123,
UserName = "foobar"
};

await UpdateUs(u);
  • Note that the above code does not set any values for Age and Password

    • AND YOU MUST NOT STORE USERS' PASSWORDS AS PLAINTEXT!
  • ...but then your code calls DbContext.Update...

    • ...which basically tells EF that "this object u now represents the current-state of the entity with Id = 123 including the fact that Age = null", which is not what you want.
      • I assume what you actually want is for EF to only consider the UserName property as updated and to ignore the other non-key properties (Password and Age) which have not yet been set.
  • Also, I get the feeling that you're using your entity classes as mutable view-models (e.g. in ASP.NET or WPF). You should not do that because an entity object represents persisted business-data state, it does not represent in-memory mutable UI state.

    • Also, view-models need additional annotations and members that entity types don't have. For example, an "Edit User" view-model needs two password fields ("New password" and "Confirm new password"), this is why we have separate classes for view-models even when they have the same members as an entity class.

Anyway, the correct solution for this (assuming that you still want to use your class User as an internal DTO), is to use Attach and set IsModified on the properties you're updating.

Like so:

    public async Task< UpdateUserAsync(User u)
{
// Preconditions:
if( u is null ) throw new ArgumentNullException(nameof(u));
if( u.Id == default ) throw new ArgumentException( message: "User's Id is not set.", paramName: nameof(u) );

//

this.dbContext.Users.Attach( u );

var entry = this.dbContext.Entry( u );
if( u.UserName != null ) entry.Property( x => x.UserName ).IsModified = true;
if( u.Age != null ) entry.Property( x => x.Age ).IsModified = true;

this.dbContext.Configuration.ValidateOnSaveEnabled = false; // <-- Only do this if necessary.

Int32 rowCount = await this.dbContext.SaveChangesAsync();
if( rowCount != 1 ) throw new InvalidOperationException( "No rows (or too many rows) were updated." );
}

EF 6 Code First - Integer primary key - Cannot insert the value NULL into column

You can't add an identity to an existing column in SQL Server.

Adding an identity to an existing column

Suggested fix is to create a new column. The best approach is to add a new identity column, create a migration for it then remove the old column and create a migration for that. This way EF wont just try and rename the old column.

Entity Framework Cannot insert the value NULL into column Identity Specification set to No

I did the following to rectify this issue:

1.) Delete the problematic table through management studio.

2.) Make sure the model is amended to have the actual Id (the thing you want as the Identity Specification set to Yes for)

3.) Through the Package Manager Console create a new migration, something like:

add-migration "Set ImportantId as Identity Specification"

4.) If nothings changed you will see an empty Up() and Down() method

5.) Modify these with the contents of the migration that initially introduced this table but make sure you set the Id to an int this time, so this:

public partial class addedimportantcasetable : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ImportantCases",
c => new
{
ImportantId = c.String(nullable: false, maxLength: 128),
EvpId = c.Int(nullable: false),
Comment = c.String(),
CategoryId = c.Int(nullable: false),
})
.PrimaryKey(t => t.ImportantId);
}

public override void Down()
{
DropTable("dbo.ImportantCases");
}
}

Is copied into the new migration, but slightly altered to this:

public partial class SetImportantIdasIdentitySpecification : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ImportantCases",
c => new
{
ImportantId = c.Int(nullable: false, identity: true),
EvpId = c.Int(nullable: false),
Comment = c.String(),
CategoryId = c.Int(nullable: false),
})
.PrimaryKey(t => t.ImportantId);
}

public override void Down()
{
DropTable("dbo.ImportantCases");
}
}


Related Topics



Leave a reply



Submit