-1

Ok, so this problem seems to have lots of different answers on SO - but I can't find a duplicate that solves my issue or makes it clear to me what the problem is. The problem arises when I try to insert/create and is a validation error on db.SaveChanges(). First of all, I was getting a "Model must have an id" message under validation in the debugger. Of course, first of all my id was a string which I figured out doesn't make sense after reading this.How to generate and auto increment Id with Entity Framework I then changed my id to an int and removed the [Key] data annotations as per the link solution above. I also updated the db. However, the id now shows as 0 and I get a validation error saying "Cannot insert the value NULL into column id in..." However, if I hard code an id the table is updated fine. Here is code.. any help appreciated. The model:

    public class Model
{
    //[Key]
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ModelId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    [DataType(DataType.Time)]
    public DateTime OpenTime { get; set; }

    [Required]
    [DataType(DataType.Time)]
    public DateTime CloseTime { get; set; }

    //Navigation property
    public virtual ICollection<OtherModel> OtherModels { get; set; }
}

The controller:

    // GET: Model/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Model/Create
    [HttpPost]
    public ActionResult Create(Model model)
    {
        try
        {
            db.Models.Add(model);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View(model);
        }
    }
Community
  • 1
  • 1
Inkers
  • 219
  • 7
  • 27
  • You do need those attributes you have commented out. –  Apr 14 '16 at 22:05
  • Are you using SQL Server? – Henrique Apr 14 '16 at 22:13
  • What is the name of your Id field in your db? If it is different from your model, how are you mapping it? – tcrite Apr 14 '16 at 22:16
  • Both match.. eg ModelId => ModelId – Inkers Apr 14 '16 at 22:18
  • This is strange because EntityFramework throws an error when you have an Entity without Key attribute – Henrique Apr 14 '16 at 22:19
  • 1
    Why did you remove the `DatabaseGenerated` attribute? I think you added the Id column in the database without an identity specification. Is it even the primary key? I think you have some work to do there. Changing a primary key requires a table drop & re-create. – Gert Arnold Apr 14 '16 at 22:20
  • Yeah, I was trying with different answers I found on here and it comes from that. Hopefully not.. gonna try the answer below now. – Inkers Apr 14 '16 at 22:22
  • Just checked the code view for the table in Sql Server Object Explorer and the id is there as PK constraint. – Inkers Apr 14 '16 at 23:06

4 Answers4

1

You just have to uncomment the line that contains DatabaseGenerated(DatabaseGeneratedOption.Identity)].After that Entity framework will auto increment the id for you. Or if you want customize the id and don't want entity framework generate it for you, in this case you can replace DatabaseGenerated(DatabaseGeneratedOption.Identity)] by DatabaseGenerated(DatabaseGeneratedOption.None)].

Ramn Singh
  • 36
  • 3
  • Ef won't generate / increment key values. The annotation only serves to let EF know that the database does that. However, I think this doesn't happen here. – Gert Arnold Apr 14 '16 at 22:22
  • So, rebuilt the solution and tried this but still getting NULL exception. Would I have to update the db first? It says column does not allow nulls, but I don't think making it int? id is a solution right? – Inkers Apr 14 '16 at 22:27
  • 1
    Are you using code first in your application ? Then try to update your database via migration. To enable migrations in your application you just have to execute enable-migrations in package manager console.... – Ramn Singh Apr 14 '16 at 22:31
  • http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application for learning migrations – Ramn Singh Apr 14 '16 at 22:33
  • OK, did a migration and ran project but now my debugger has disappeared.... arrrrghhhh! Trying to get it back! – Inkers Apr 14 '16 at 22:38
  • You can find it in View or tool section of your IDE menu if i'm not wrong... Else try to put a breakpoint. – Ramn Singh Apr 14 '16 at 22:42
  • Ran it again... no joy... context is there etc... just shows id value as "0" and throws null exception... stumped... maybe something I did to db.. as code first is it a big job to drop db and start from scratch... test data so no problem there. – Inkers Apr 14 '16 at 22:49
  • Did you update your database after adding a migration ? – Ramn Singh Apr 14 '16 at 22:50
  • 1
    Ok let me recapitulate everything.... 1st step : uncomment DatabaseGenerated(DatabaseGeneratedOption.Identity)] 2nd step : Enable-migrations is a command which has to be executed to enable migrations. 3rd step : add-migration name_of_the_migration is a command which will generate a class containing all modifications 4th step : at last update-database command should be executed to update your database. If you have done all the steps correctly. Normally your code should work perfectly. – Ramn Singh Apr 14 '16 at 23:10
1

Update your ModelId property as shown below and apply the migration by using the Package Manager Console.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ModelId { get; set; }

If the problem is still not solved, open the related table in design mode by using SSMS (Sql Server Management Studio). Then check if the ModelId seems to be PK and the Is Identity property is set to "Yes" as shown on the screenshot below.

IsIdentity

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63
  • OK, it worked... once! I presume I need to change .None back to .Identity? Getting a PK violation error - cannot insert duplicate – Inkers Apr 14 '16 at 23:21
  • It might be caused by incompatible PK values with the FK values of related tables. Please check if there is any incompatible value pairs in the related tables. – Murat Yıldız Apr 14 '16 at 23:24
  • OK. So I checked the foreign key in the connected table and discovered that I had forgotten to change that to an int when I changed it earlier. Thought that would be the problem but still getting duplicate error. – Inkers Apr 14 '16 at 23:42
  • @Inkers Would you please full backup your database and then delete-create the data in the table(s) that might causing the problem. I think your problem is solved, but the data added before causing the error. – Murat Yıldız Apr 14 '16 at 23:45
0

If you use SQL Server, your ModelId must be an Identity at the Database.

And every entity must have at least a key.

Henrique
  • 602
  • 4
  • 18
  • I could be wrong here, but I think Entity Framework handles the key creation for you the first time you run the code. It looks for a property with Id in it and sets as key... I think.. maybe someone else knows for sure. – Inkers Apr 14 '16 at 22:56
-1

I was going the wrong direction with this so a lot of the comments, while useful in parts may be a bit misleading for others. The problem: As Gert Arnold and Ramn Singh alluded to, I created my tables in the first place without identity: true which meant that

[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //you need to include this on your model

was doing nothing when I included it after the tables had been created. Even with an update on the database and dropping and recreating the db, the id cannot be null error persisted. And then I came across this: Reset Entity-Framework Migrations

  1. Go to Solution Explorer, Migrations, right click, delete.
  2. Go to Sql Server Object Explorer, Migrations History, right click delete, wait for script to generate and run it.
  3. Open Package Manager Console (Tools - NuGet Package Manager - Package Manager Console)
  4. Type Enable-Migrations -Force
  5. Add-Migration Initial
  6. Update-Database

For some people this throws a "table x already exists" exception. The link above mentions commenting out the "Up" part of the migration. When I tried this my project would not build. Because my data was unimportant/test, I went back into

  1. Sql Server Object Explorer, select all tables (not system), right click, delete.
  2. Return to PM Console
  3. Update Database

Run your project and interact with db. Hope this helps others.

Community
  • 1
  • 1
Inkers
  • 219
  • 7
  • 27