【发布时间】:2012-12-01 19:16:27
【问题描述】:
我正在使用 POCO 编写代码第一个实体框架应用程序。 这是简化版:
我定义了这个实体:
public class Respondent
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RespondentId { get; set; }
[Display(Name = "Your Name")]
public string Name { get; set; }
}
此实体用于创建表:
public class MyContext : DbContext
{
public DbSet<Respondent> Respondents { get; set; }
}
我还定义了一个包含这个实体的视图模型:
public class SurveyModel
{
public Respondent Respondent { get; set; }
}
现在,在代码中:
var survey = new SurveyModel();
survey.Respondent = new Respondent();
当我需要写入数据库时:
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);
此时survey.Respondent.RespondentId必须加1,因为它使用相应的属性定义为IDENTITY。
但这不会发生。 请指教我做错了什么? 谢谢。
【问题讨论】:
标签: entity-framework linq-to-entities code-first poco