使用EF获取新创建的对象的Id

时间:2015-06-18 14:39:09

标签: c# entity-framework unit-of-work

我的存储库通过UnitOfWork公开,Add方法只有以下代码:

public void Add(Employee emp)
{
    context.add(emp);
} 

然后,从UnitOfWork,我用这段代码调用Add()方法:

this.UnitOfWork.EmployeeRepository.Create(emp);
this.UnitOfWork.Commit(); // This calls SaveChanges() EF method

现在问题是我如何在这里获得新创建的对象的Id

2 个答案:

答案 0 :(得分:1)

通常,如果您的In [160]: # create a list of the iterable index values we want to generate all product combinations from iterables = [df['ID'].unique(),df['PERIOD'].unique()] iterables Out[160]: [array([1, 2, 3], dtype=int64), array([1, 2, 3, 4, 5, 6], dtype=int64)] In [163]: # set the index to ID and PERIOD df = df.set_index(['ID','PERIOD']) df Out[163]: VAlUE ID PERIOD 1 1 10 2 8 3 8 4 15 5 6 6 44 2 1 NONE 3 2 4 5 25 In [164]: # reindex and pass the product from iterables as the new index df.reindex(index=pd.MultiIndex.from_product(iterables, names=['ID', 'PERIOD']), fill_value='NONE').reset_index() Out[164]: ID PERIOD VAlUE 0 1 1 10 1 1 2 8 2 1 3 8 3 1 4 15 4 1 5 6 5 1 6 44 6 2 1 NONE 7 2 2 NONE 8 2 3 NONE 9 2 4 NONE 10 2 5 NONE 11 2 6 NONE 12 3 1 NONE 13 3 2 4 14 3 3 NONE 15 3 4 NONE 16 3 5 25 17 3 6 NONE 是身份,则在保存更改时,Id将自动填充。

Id

第二种变体可能是使用GetDatabaseValues方法:

context.Employees.Add(emp);
context.SaveChanges();
var newId=emp.Id; //The Id is filled after save changes

答案 1 :(得分:0)

SaveChanges之后,员工实体将分配新的ID。找到一种方法将其返回到更高级别的方法。

相关问题