我正在使用 Dapper plus 批量插入 SQL 表。我在维护主表和详细表之间的引用完整性方面面临挑战。 这是代码。
var userName = Environment.UserName;
DapperPlusManager.Entity<HardwareComponentType>("WithInsertIfNotExists").Table("dbo.HardwareComponents")
.UseBulkOptions(options => {
options.InsertIfNotExists = true;
}).Identity(x=>x.ComponentId).Map("Name", "Name").Map("Status", "Status").MapValue(DateTime.Now, "ModifiedDateTime").MapValue(userName, "ModifiedByUser");
DapperPlusManager.Entity<HardwareComponent>()
.Table("dbo.HardwareComponentDetails").Identity(x=>x.ComponentDetailsId).Map("NodeID", "NodeID").Map("Name","Name").Map("Level", "Level").Map("Status", "Status").Map("DateSinceOperational", "DateSinceOperational").Map("IsWorkAssigned", "IsWorkAssigned");
var hardwareComponents = hardwareComponentTypes.SelectMany(x => x.Components.Where(y => y.NodeID != null)).ToList();
//bulk insert here
dbConnection.BulkInsert(hardwareComponentTypes).ThenBulkInsert(hardwareComponent=> hardwareComponent.Components );
这是我的类结构(主对象):
public class HardwareComponentType
{
/// <summary>
/// ComponentId.
/// </summary>
[Key]
public int ComponentId { get; set; }
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Status.
/// </summary>
public string Status { get;set;}
public int Order { get; set; }
/// <summary>
/// Components List.
/// </summary>
public List<HardwareComponent> Components { get; set; }
}
详细对象
public class HardwareComponent
{
/// <summary>
/// Component DetailsId.
/// </summary>
[Key]
public int ComponentDetailsId { get; set; }
/// <summary>
/// ComponentId.
/// </summary>
public int ComponentId { get; set; }
/// <summary>
/// NodeId.
/// </summary>
public string NodeID { get; set; }
/// <summary>
/// Level.
/// </summary>
public int? Level { get; set; }
/// <summary>
/// Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Status.
/// </summary>
public string Status { get; set; }
/// <summary>
/// Date Since Operational.
/// </summary>
public DateTime? DateSinceOperational { get; set; }
/// <summary>
/// Is Work Assigned.
/// </summary>
public bool? IsWorkAssigned { get; set; }
}
如您所见,主表主键(ComponentId)是明细表中的外键。 我希望当记录插入到详细表中时,它应该从组件表中获取相应的ComponentId。
那么,我应该做两个单独的插入语句还是当前语句就足够了?否则我如何实现引用完整性:
dbConnection.BulkInsert(hardwareComponentTypes).ThenBulkInsert(hardwareComponent=> hardwareComponent.Components );
我希望当记录插入明细表时,它应该从组件表中获取相应的ComponentId。
您可以在映射中使用以下解决方案之一:
如:
DapperPlusManager.Entity<HardwareComponentType>("WithInsertIfNotExists").Table("dbo.HardwareComponents")
.UseBulkOptions(options => {
options.InsertIfNotExists = true;
}).Identity(x=>x.ComponentId).Map("Name", "Name").Map("Status", "Status").MapValue(DateTime.Now, "ModifiedDateTime").MapValue(userName, "ModifiedByUser")
.AfterAction((actionKind, master) =>
{
if (actionKind == DapperPlusActionKind.Insert || actionKind == DapperPlusActionKind.Merge)
{
if (master.Components != null)
{
master.Components.ForEach(x => x.ComponentId = master.ComponentId);
}
}
});