Can#39;t auto-generate IDENTITY with AddRange in Entity Framework(无法在实体框架中使用 AddRange 自动生成 IDENTITY)
问题描述
我不知道这是实体框架的设计选择还是代表我的错误方法,但每当我尝试将实体添加到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法在实体框架中使用 AddRange 自动生成 IDENTITY
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01