Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 获取刚刚保存到数据库MVC4 ASP.Net的模型的记录id_Entity Framework_Asp.net Mvc 4 - Fatal编程技术网

Entity framework 获取刚刚保存到数据库MVC4 ASP.Net的模型的记录id

Entity framework 获取刚刚保存到数据库MVC4 ASP.Net的模型的记录id,entity-framework,asp.net-mvc-4,Entity Framework,Asp.net Mvc 4,使用ASP.Net/C#和MVC4和EF5。我有一个基础模型,其中几个其他模型通过id链接 public class Person { public int Id { get; set; } public DateTime? Created { get; set; } public DateTime? Submitted { get; set; } public DateTime? Finalized { get; set

使用ASP.Net/C#和MVC4和EF5。我有一个基础模型,其中几个其他模型通过id链接

 public class Person
    {
        public int Id { get; set; }
        public DateTime? Created { get; set; }
        public DateTime? Submitted { get; set; }
        public DateTime? Finalized { get; set; }

        public string UserProfileSite { get; set; }
        public int UserId { get; set; }

        public virtual ICollection<Demographic> Demographics { get; set; }
        public virtual ICollection<Demographic> Demographics { get; set; }
     }

如何获取我刚刚保存到数据库中的记录的personId,以便将其传递给我的人口统计数据,以便模型具有personId的外键

假设您没有在entity framework中启用changeTracking,那么在将对象保存到数据库后,您应该能够简单地获取该对象的id

Person person = new Person();
person.UserId = curuser.UserId;
person.UserProfileSite = curuser.Site;
person.Created = DateTime.Now;
db.Persons.Add(person);
db.SaveChanges();
var personId = person.Id;

谢谢你的快速回复。
Person person = new Person();
person.UserId = curuser.UserId;
person.UserProfileSite = curuser.Site;
person.Created = DateTime.Now;
db.Persons.Add(person);
db.SaveChanges();
var personId = person.Id;