EF Core - 为什么实体在应该是外键关系时被保存为新的数据库实体?
EF Core - Why are entities being saved as new DB entities when they should be Foreign Key Relationships?
我们的上下文不再使用 EF6 DB 优先模型 - 我正在构建一个 ASP Core API,它使用 EF Core Code First 模型作为数据库上下文。要在滚动更新中执行此操作,我的上下文必须存在于当前数据库架构中,因此我使用 EF Fluent API 为不反映当前数据库架构的代码优先模型构建我的实体映射。
我在插入操作期间遇到了实体上导航属性的问题。使用标准 .Include(x => x.OtherEntity) 格式从数据库获取主要实体的数据效果很好,将主要实体保存回数据库就是问题所在。
使用 Fluent API 映射实体对我来说是新的,因此学习曲线可能是我的问题所在。我曾尝试使用 OwnsOne 与 HasOne,但 MS 文档表明 HasOne() 是执行此映射的正确方法。
我所讨论的主要实体具有外键字段的影子属性,当我在流畅的映射中使用 .HasOne()(在下面的代码中)link 时,这些键 linked
异常消息在这种情况下没有用,因为它们没有反映映射问题,它们表明当导航属性的表具有标识列时无法插入数据(即无法插入具有显式 ID 的记录)-> 这很奇怪,因为我没有尝试通过这些导航属性插入数据,我只是想 link 我的主要实体到具有外键的次要实体。
实体映射:
// WorkOrder Entity Mapping:
modelBuilder.Entity<WorkOrder>().ToTable("WorkOrder");
modelBuilder.Entity<WorkOrder>().Property(x => x.Id).HasColumnName("IDWorkOrder");
modelBuilder.Entity<WorkOrder>().Property(x => x.CreatedBy).HasColumnName("IDUserCreated");
modelBuilder.Entity<WorkOrder>().Property(x => x.UpdatedBy).HasColumnName("IDUserUpdated");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOCategory");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDProblem");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOCostCenter");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOLocation");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOPriority");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOStatus");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOTrade");
modelBuilder.Entity<WorkOrder>().Property<Guid?>("IDUserCompleted");
modelBuilder.Entity<WorkOrder>().Property<Guid?>("IDParentWO");
// WO Navigation Properties:
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Category).WithOne().HasForeignKey<WorkOrder>("IDWOCategory").HasPrincipalKey<Category>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Problem).WithOne().HasForeignKey<WorkOrder>("IDProblem").HasPrincipalKey<Problem>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.CostCenter).WithOne().HasForeignKey<WorkOrder>("IDWOCostCenter").HasPrincipalKey<CostCenter>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Location).WithOne().HasForeignKey<WorkOrder>("IDWOLocation").HasPrincipalKey<Location>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Priority).WithOne().HasForeignKey<WorkOrder>("IDWOPriority").HasPrincipalKey<Priority>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Status).WithOne().HasForeignKey<WorkOrder>("IDWOStatus").HasPrincipalKey<Status>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Trade).WithOne().HasForeignKey<WorkOrder>("IDWOTrade").HasPrincipalKey<Trade>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Requester).WithOne().HasForeignKey<WorkOrder>("IDRequester").HasPrincipalKey<Requester>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.UserCompleted).WithOne().HasForeignKey<WorkOrder>("IDUserCompleted").HasPrincipalKey<User>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.ParentWorkOrder).WithOne().HasForeignKey<WorkOrder>("IDParentWO").HasPrincipalKey<WorkOrder>(c => c.Id);
获取控制器中的数据:(非常棒!)
[HttpGet("{Id}")]
public async Task<ActionResult<List<WorkOrder>>> GetWorkOrders(Guid Id)
{
var result = await WorkOrdersContext.WorkOrders
.Include(x => x.Problem)
.Include(x => x.Status)
.Include(x => x.Requester)
.Include(x => x.ParentWorkOrder)
.Include(x => x.Category)
.Include(x => x.Trade)
.Include(x => x.Location)
.Include(x => x.CostCenter)
.Include(x => x.Priority)
.Where(x => x.Id == Id)
.ToListAsync();
return Ok(result);
}
在控制器中保存新数据:(哪里出了问题!)
[HttpPost]
public async Task<ActionResult<WorkOrder>> CreateWorkOrderFromPending([FromBody]WorkOrder call)
{
// Insert the Work Order to the DB:
DbContext.WorkOrders.Add(call);
var saveResult = await DbContext.SaveChangesAsync();
// Check if any oddities occurred during the save:
if (saveResult == 0) return BadRequest("An Error occurred during saving and the Call was not saved, please try again.");
// Return the Inserted Work Order:
return Ok(call);
}
在这里,当它尝试保存新工作订单时,由于映射类型(实体映射代码片段中的问题、类别、成本中心等)而抛出异常它正在尝试将数据保存为新实体而不是在现有实体上建立 FK 关系。我认为这是我在 Fluent API!
中缺少一些逻辑的地方
任何帮助将不胜感激,因为在 google 搜索中很难用几个词来表达这个问题!
感谢@DavidBrowne-Microsoft,我得到了答案,试图让我们过去的 DB First 与 .NET Core 共存并非易事,而且来自 Code First 背景,其中 .Add() 是行之有效的路径,让人很难看出 .Attach() 是如何做到这一点的。
[HttpPost]
public async Task<ActionResult<WorkOrder>> CreateWorkOrderFromPending([FromBody]WorkOrder call)
{
// Insert the Work Order to the DB:
// DbContext.WorkOrders.Add(call);
var entity = DbContext.WorkOrders.Attach(call);
entity.State = EntityState.Added;
var saveResult = await DbContext.SaveChangesAsync();
// Check if any oddities occurred during the save:
if (saveResult == 0) return BadRequest("An Error occurred during saving and the Call was not saved, please try again.");
// Return the Inserted Work Order:
return Ok(call);
}
使用 .Attach() 而不是 .Add() 成功了,将实体放入并将 FK 从我的 Fluent 映射映射到它们各自的阴影属性!
我们的上下文不再使用 EF6 DB 优先模型 - 我正在构建一个 ASP Core API,它使用 EF Core Code First 模型作为数据库上下文。要在滚动更新中执行此操作,我的上下文必须存在于当前数据库架构中,因此我使用 EF Fluent API 为不反映当前数据库架构的代码优先模型构建我的实体映射。
我在插入操作期间遇到了实体上导航属性的问题。使用标准 .Include(x => x.OtherEntity) 格式从数据库获取主要实体的数据效果很好,将主要实体保存回数据库就是问题所在。
使用 Fluent API 映射实体对我来说是新的,因此学习曲线可能是我的问题所在。我曾尝试使用 OwnsOne 与 HasOne,但 MS 文档表明 HasOne() 是执行此映射的正确方法。
我所讨论的主要实体具有外键字段的影子属性,当我在流畅的映射中使用 .HasOne()(在下面的代码中)link 时,这些键 linked
异常消息在这种情况下没有用,因为它们没有反映映射问题,它们表明当导航属性的表具有标识列时无法插入数据(即无法插入具有显式 ID 的记录)-> 这很奇怪,因为我没有尝试通过这些导航属性插入数据,我只是想 link 我的主要实体到具有外键的次要实体。
实体映射:
// WorkOrder Entity Mapping:
modelBuilder.Entity<WorkOrder>().ToTable("WorkOrder");
modelBuilder.Entity<WorkOrder>().Property(x => x.Id).HasColumnName("IDWorkOrder");
modelBuilder.Entity<WorkOrder>().Property(x => x.CreatedBy).HasColumnName("IDUserCreated");
modelBuilder.Entity<WorkOrder>().Property(x => x.UpdatedBy).HasColumnName("IDUserUpdated");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOCategory");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDProblem");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOCostCenter");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOLocation");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOPriority");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOStatus");
modelBuilder.Entity<WorkOrder>().Property<int?>("IDWOTrade");
modelBuilder.Entity<WorkOrder>().Property<Guid?>("IDUserCompleted");
modelBuilder.Entity<WorkOrder>().Property<Guid?>("IDParentWO");
// WO Navigation Properties:
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Category).WithOne().HasForeignKey<WorkOrder>("IDWOCategory").HasPrincipalKey<Category>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Problem).WithOne().HasForeignKey<WorkOrder>("IDProblem").HasPrincipalKey<Problem>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.CostCenter).WithOne().HasForeignKey<WorkOrder>("IDWOCostCenter").HasPrincipalKey<CostCenter>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Location).WithOne().HasForeignKey<WorkOrder>("IDWOLocation").HasPrincipalKey<Location>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Priority).WithOne().HasForeignKey<WorkOrder>("IDWOPriority").HasPrincipalKey<Priority>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Status).WithOne().HasForeignKey<WorkOrder>("IDWOStatus").HasPrincipalKey<Status>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Trade).WithOne().HasForeignKey<WorkOrder>("IDWOTrade").HasPrincipalKey<Trade>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.Requester).WithOne().HasForeignKey<WorkOrder>("IDRequester").HasPrincipalKey<Requester>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.UserCompleted).WithOne().HasForeignKey<WorkOrder>("IDUserCompleted").HasPrincipalKey<User>(c => c.Id);
modelBuilder.Entity<WorkOrder>().HasOne(x => x.ParentWorkOrder).WithOne().HasForeignKey<WorkOrder>("IDParentWO").HasPrincipalKey<WorkOrder>(c => c.Id);
获取控制器中的数据:(非常棒!)
[HttpGet("{Id}")]
public async Task<ActionResult<List<WorkOrder>>> GetWorkOrders(Guid Id)
{
var result = await WorkOrdersContext.WorkOrders
.Include(x => x.Problem)
.Include(x => x.Status)
.Include(x => x.Requester)
.Include(x => x.ParentWorkOrder)
.Include(x => x.Category)
.Include(x => x.Trade)
.Include(x => x.Location)
.Include(x => x.CostCenter)
.Include(x => x.Priority)
.Where(x => x.Id == Id)
.ToListAsync();
return Ok(result);
}
在控制器中保存新数据:(哪里出了问题!)
[HttpPost]
public async Task<ActionResult<WorkOrder>> CreateWorkOrderFromPending([FromBody]WorkOrder call)
{
// Insert the Work Order to the DB:
DbContext.WorkOrders.Add(call);
var saveResult = await DbContext.SaveChangesAsync();
// Check if any oddities occurred during the save:
if (saveResult == 0) return BadRequest("An Error occurred during saving and the Call was not saved, please try again.");
// Return the Inserted Work Order:
return Ok(call);
}
在这里,当它尝试保存新工作订单时,由于映射类型(实体映射代码片段中的问题、类别、成本中心等)而抛出异常它正在尝试将数据保存为新实体而不是在现有实体上建立 FK 关系。我认为这是我在 Fluent API!
中缺少一些逻辑的地方任何帮助将不胜感激,因为在 google 搜索中很难用几个词来表达这个问题!
感谢@DavidBrowne-Microsoft,我得到了答案,试图让我们过去的 DB First 与 .NET Core 共存并非易事,而且来自 Code First 背景,其中 .Add() 是行之有效的路径,让人很难看出 .Attach() 是如何做到这一点的。
[HttpPost]
public async Task<ActionResult<WorkOrder>> CreateWorkOrderFromPending([FromBody]WorkOrder call)
{
// Insert the Work Order to the DB:
// DbContext.WorkOrders.Add(call);
var entity = DbContext.WorkOrders.Attach(call);
entity.State = EntityState.Added;
var saveResult = await DbContext.SaveChangesAsync();
// Check if any oddities occurred during the save:
if (saveResult == 0) return BadRequest("An Error occurred during saving and the Call was not saved, please try again.");
// Return the Inserted Work Order:
return Ok(call);
}
使用 .Attach() 而不是 .Add() 成功了,将实体放入并将 FK 从我的 Fluent 映射映射到它们各自的阴影属性!