问题描述
我不知道这是实体框架的设计选择还是代表我的错误方法,但每当我尝试将实体添加到 DbSet 时,我似乎都无法获得自动生成的 IDENTITY 字段.
I don't know if it's an Entity Framework's desing choice or a wrong approach on my behalf, but whenever I try to AddRange entities to a DbSet I can't seem to get the auto-generated IDENTITY fields.
[Table("entities")]
public class Entity
{
[Key]
[Column("id")]
public long Id { get; set; }
[Column("field")]
public string Field { get; set; }
}
var entities = new Entity[]
{
new Entity() { Field = "A" },
new Entity() { Field = "B" },
};
_dbContext.Entities.AddRange(entities);
await _dbContext.SaveChangesAsync();
//ids are still default(long) at this point!!
这是更新的代码以显示导致问题的原因:enumerables.无需在实体类中添加其他属性.
Here's the updated code to show what was causing the problem: enumerables. No need to add other attributes to the entity classes.
public class Request
{
public string Field { get; set; }
public Entity ToEntity()
{
return new Entity() { Field = Field };
}
}
public async Task<IEnumerable<long>> SaveRequests(IEnumerable<Request> requests)
{
var entities = requests.Select(r => r.ToEntity()); //not working
var entities = requests.Select(r => r.ToEntity()).ToArray(); //working
_dbContext.Entities.AddRange(entities);
await _dbContext.SaveChangesAsync();
return entities.Select(e => e.Id);
}
推荐答案
是什么导致了问题?可数!请查看我的问题中的 EDIT 部分以获取解决方案.
What was causing the problem? Enumerables! Take a look at the EDIT section in my question for the solution.
在此处发布更新的代码作为答案.问题在于我使用枚举的方式.最重要的是,当您需要立即获得一致的结果时,您永远不应该相信延迟加载.
posting the updated code here as answer. The problem was in the way I used enumerables. Bottom line is you should never trust lazy loading when you need consistent results right away.
public class Request
{
public string Field { get; set; }
public Entity ToEntity()
{
return new Entity() { Field = Field };
}
}
public async Task<IEnumerable<long>> SaveRequests(IEnumerable<Request> requests)
{
var entities = requests.Select(r => r.ToEntity()); //not working
var entities = requests.Select(r => r.ToEntity()).ToArray(); //working
_dbContext.Entities.AddRange(entities);
await _dbContext.SaveChangesAsync();
return entities.Select(e => e.Id);
}
这篇关于无法在实体框架中使用 AddRange 自动生成 IDENTITY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!