Framework中的AddRange自动生成IDENTITY

Framework中的AddRange自动生成IDENTITY

本文介绍了无法使用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!!

这是更新的代码,以显示引起问题的原因:枚举.无需向实体类添加其他属性.

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.

这篇关于无法使用Entity Framework中的AddRange自动生成IDENTITY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:29