我不知道这是代表 Entity Framework 的选择,还是代表我的方法错误,但是每当我尝试将实体添加到DbSet时,我似乎都无法获得自动生成的IDENTITY字段。

[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!!

编辑:
这是更新的代码,以显示引起问题的原因:枚举。无需向实体类添加其他属性。
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 部分,以寻求解决方案。
编辑:在此处发布更新的代码作为答案。问题出在我使用枚举的方式上。最重要的是,当您需要立即获得一致的结果时,您永远不应该信任延迟加载。

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);
}

10-08 07:18