首先您的“使用”声明很奇怪。 应该
using (var context = new MyContext()) //passing in optional connection string.
{
}
然后您访问实体似乎奇数或我不知道自己在做什么的方式出现...
var updatedObjects = localContext.ChangeTracker.Entries().Where(e => e.Entity is GenerationEvent && (e.State == EntityState.Modified || e.State == EntityState.Added));
var updatedEvents = updatedObjects.Select(e => (GenerationEvent)e.Entity);
好像你所要求的所有项目上下文这被视为“添加”或“更新”
然后您正在接受对上下文的更改。例如SaveChanges()。
在调用save-changes之后,我完全期待“updatedEvents”为空。
更改你的东西...喜欢的东西
using (var context = new MyContext()) //passing in optional connection string.
{
LIst<EntityType> listOfChangedEntities = //ToDo:either passed in or generated
context.EntityType.AddRandge(listOfChangedEntities);
context.SaveChanges();
//after SaveChanges has been done all the entities in the
//listOfChangedEntities will now have there id's
//for update, fetch the entities... change them and Update them
}
我怀疑你正试图建立某种形式的通用代码来处理任何类型的实体,而无需指定其类型。你的代码不适合这样,如果这是你想要做的,我会修改这个问题来问你想要达到的目标。但是,以上是获取插入实体的Id的正常方式。
您可以通过谈论的其他示例是他们使用外键和导航属性自动关联相关实体的位置,但您的代码看起来与此无关。
UPDATE
常规
public static DoWork()
{
var context = new MyContext();
List<GenerationEvent > internalEntityType = new List<GenerationEvent();
foreach(var item in SomeList)
{
var newItemEntity = new GenerationEvent();
newItemEntity.Name = "Test";
context.GenerationEvent.Add(newItemEntity);
//add to internal list
internalEntityType.Add(newItemEntity)
}
context.SaveChanges();
var first_id = internalEntityType.FirstOrDefault().Id;
//first_id will not be 0 it will be the Id the database gave it.
}
'updatedEvents'不是'list',但再次执行任何时候你列举它的LINQ查询。如果你想缓存它以备后用,把'.ToList()'放在'updateEvents'赋值行的末尾。 –