0

I am working on a project that uses EF created with code first approach. The model was created by someone else. In the database table there was no primary key and all the fields were mandatory. Now we need a column to be auto incremented primary key and another column to be optional. We have made these changes in the database table but we are getting 'Entity Validation Error' since we are not passing the "ID"(probably the reason). What are the changes and where should they be written? Here is the class that was created:

public int ID { get; set; }//This needs to be auto incremented primary key.
public int UserID{ get; set; }
public string Name { get; set; }
public string Address { get; set; }
public bool IsActive { get; set; }
public bool Deleted { get; set; }
public int ModifiedBy { get; set; }
public System.DateTime DateCreated { get; set; }
public System.DateTime DateModified { get; set; }//This field needs to be optional.
user1640256
  • 1,691
  • 7
  • 25
  • 48

1 Answers1

0

You need to set the Key and DatabaseGenerated attributes for the new Id Property.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
Suresh Kumar Veluswamy
  • 4,193
  • 2
  • 20
  • 35
  • I have already tried that. I am still getting the error: "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details" – user1640256 Mar 20 '14 at 12:05
  • Can you catch the DbEntityValidationException and see what is present in the list of errors? http://stackoverflow.com/a/7798264/1305119 – Suresh Kumar Veluswamy Mar 20 '14 at 12:07
  • I can't hit the debugger because I am using ASP.Net Web API controller. – user1640256 Mar 20 '14 at 12:17
  • Then you can write the exception to a file....http://stackoverflow.com/a/16619043/1305119 – Suresh Kumar Veluswamy Mar 20 '14 at 12:27
  • I made both the projects as start up project to enable debugging. I could get the exception. The inner exception states "Can not insert NULL into column ID". This is my primary key column that I need to be auto incremented and identity. – user1640256 Mar 20 '14 at 12:47