CallumVass
CallumVass

Reputation: 11448

ASP.NET MVC / EF - Manually assign an ID (PK)

Whenver I try to insert a new row into my table manually, I get the following error:

Cannot insert the value NULL into column 'VehicleID', table 'TestServer.Vehicles'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Even tho I have set the VehicleID in my code, like so:

List<Vehicles> vehicleList = context.Vehicles.ToList();

if(vehicleList.Count == 0)
{
     vehicle.VehicleID = 1;
}
else 
{
     vehicle.VehicleID = vehicleList.Last().VehicleID + 1;
}

context.Vehicles.Add(vehicle);
context.SaveChanges();

// Other code...

The reason I need to do this is because in this Action, I am actually updating another Model, but I also want to update my Vehicle model, based on the other model im updating

My VehicleID property has the [Key] data annotation set, could this be a reason why?

Upvotes: 3

Views: 1532

Answers (1)

Slauma
Slauma

Reputation: 177133

One possible reason is that you don't have marked the key property in your model as not database generated. You can do this either with data annotations...

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

    //...
}

...or with Fluent API:

modelBuilder.Entity<Vehicle>()
    .Property(v => v.VehicleID)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

For Integer keys EF assumes by default that the column is an autogenerated identity in the database and therefore doesn't send the value of the ID to the server. If the column isn't autogenerated in the DB you get the error.

Upvotes: 8

Related Questions