实体框架保存新对象返回填充ID?

时间:2014-05-15 16:55:10

标签: entity-framework

请帮助我理解这一点。

当我将新对象保存到数据库(使用Entity Framework)时,我可以在调用db.SaveChanges()之后访问行中新创建的ID(标识列)值吗?

public Class TheObject
{
    public int ID { get; set; }
    public string FirstName { get; set; }
}

.....

TheObject MyObject = new TheObject();
MyObject.FirstName = "John";

db.TheObjects.Add(MyObject);
db.SaveChanges();

int MyNewID = MyObject.ID; //Am I able to access MyObject.ID here and have access to the value that was just created in the database?

1 个答案:

答案 0 :(得分:1)

是的,但是为什么不运行该代码并自行测试呢?