I am writing code first Entity Framework app using POCO.
Here is simplified version:
I defined this entity:
public class Respondent
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RespondentId { get; set; }
[Display(Name = "Your Name")]
public string Name { get; set; }
}
This entity is used to create a table:
public class MyContext : DbContext
{
public DbSet<Respondent> Respondents { get; set; }
}
I also defined a View Model that contains this entity:
public class SurveyModel
{
public Respondent Respondent { get; set; }
}
Now, in code:
var survey = new SurveyModel();
survey.Respondent = new Respondent();
When I need to write to the DB:
private MyContext db = new MyContext();
// HERE, after this line, SHOULD survey.Respondent.RespondentId be +1 ??
// Or only when I call db.SaveChanges() ??
db.Respondents.Add(survey.Respondent);
At this moment survey.Respondent.RespondentId must be increased by 1 since it is defined as IDENTITY using the corresponding attribute.
But it doesn’t happen.
Please advice what I am doing wrong?
Thank you.
You need to call db.SaveChanges() in order for it to be saved to the database.