对于ID,如何使用带有标识列的MSSQL,在调用BulkInsert之后如何获得与表ID同步的实体ID?
context.BulkInsert(entities);两者均未达到所要求的结果:
context.BulkSynchronize(entities);
context.BulkMerge(entities);假设我们有一个实体
var newSomething = new Something { Id = 0 };和相应的TSQL表列定义。
ID int IDENTITY(1,1)实体框架调用SaveChanges()后自动设置Id
context.SomethingSet.Add(newSomething);
context.SaveChanges();
Assert.IsTrue(newSomething.Id != 0)EFPlus如何提供获取插入实体的Id的方法?
发布于 2018-05-18 05:52:14
免责声明:我是项目实体框架扩展的所有者
默认情况下,Entity Framework Extensions库应该已经返回插入实体的ids。
例如,下面的代码在与BulkInsert一起使用时应该已经工作并返回ids。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Windows.Forms;
namespace Z.EntityFramework.Extensions.Lab
{
public partial class Form_Request_Ids : Form
{
public Form_Request_DateNull()
{
InitializeComponent();
// CLEAR
using (var ctx = new CurrentContext())
{
ctx.EntitySimples.RemoveRange(ctx.EntitySimples);
ctx.SaveChanges();
}
// TEST
using (var ctx = new CurrentContext())
{
var list = new List<EntitySimple>();
list.Add(new EntitySimple() { Id = 0, IntColumn = 1, CreatedDate = DateTime.Now });
ctx.BulkInsert(list);
}
}
public class CurrentContext : DbContext
{
public CurrentContext()
: base("CodeFirstEntities")
{
}
public DbSet<EntitySimple> EntitySimples { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Types().Configure(x => x.ToTable(GetType().DeclaringType != null ? GetType().DeclaringType.FullName.Replace(".", "_") + "_" + x.ClrType.Name : ""));
base.OnModelCreating(modelBuilder);
}
}
public class EntitySimple
{
public int Id { get; set; }
public int IntColumn { get; set; }
public DateTime CreatedDate { get; set; }
}
}
}如果您仍然有这个问题,请尝试与我们直接联系一个示例info@zzzprojects.com或张贴您的例子在这里。
https://stackoverflow.com/questions/50344795
复制相似问题