You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF6中实体表存在但无法通过模型访问的问题求助

解决EF6新增表后上下文无法识别DbSet的问题

问题场景

在Visual Studio 2019中使用C#、.NET 4.6和EF 6.1.3开发,数据库新增DebtCollectionBatch表并刷新EF模型后,代码访问时抛出异常:

System.InvalidOperationException: The entity type DebtCollectionBatch is not part of the model for the current context

异常触发在DbSet.Add方法处。多次刷新模型、删除原模型重启VS重建后,仍能实例化DebtCollectionBatch对象,但无法通过SuburbanWebServiceEntities上下文访问对应DbSet。连接字符串、数据库表结构均正常,代码中输入entity.d时无法找到对应集合。

相关代码片段

public bool SaveDebtCollectionsBatchTotal(BatchTotalDebtCollections batchTotal)
{
  var dt = DateTime.Now.ToUniversalTime();
  try
  {
    using (var entity = new SuburbanWebServiceEntities())
    {
      var bt = new DebtCollectionBatch();
      bt.DebtCollectionsBatchId = Guid.NewGuid();
      bt.DebtCollectionsCount = batchTotal.AchCount;
      bt.DebtCollectionsCompany = batchTotal.DebtCollectionsCompany;
      bt.CompanyCode = batchTotal.CompanyCode;
      bt.DateTimeSubmitted = DateTime.Now;
      bt.DollarTotal = batchTotal.DollarTotal;
      entity.d  // <-- 此处无法找到DebtCollectionBatch对应的DbSet
      entity.SaveChanges();
      WriteLog.WriteToLogFile("SaveDebtCollectionsBatchTotal", 
        $"Successfully saved ach transactions for {batchTotal.CompanyCode} on {dt}.");
    }
    return true;
  }
  catch (Exception ex)
  {
    WriteLog.WriteToLogFile("SaveDebtCollectionsBatchTotal", 
      $"Failed to save debt collection batch total...", ex);
    return false;
  }
}

解决建议

  • 检查EDMX实体映射
    打开EDMX设计器,确认DebtCollectionBatch实体已正确生成,且与数据库表的映射关系完整(包括主键、字段对应)。若映射缺失,手动添加实体并关联到目标表。
  • 手动添加DbSet到上下文
    若EDMX刷新后上下文类未自动生成DbSet<DebtCollectionBatch>,手动在SuburbanWebServiceEntities类中添加:
    public DbSet<DebtCollectionBatch> DebtCollectionBatches { get; set; }
    
  • 清理并重建项目
    执行清理解决方案后再重建解决方案,确保旧的生成文件被替换,上下文类得到更新。
  • 检查EDMX代码生成策略
    右键EDMX文件→属性,确认“代码生成策略”设置为“默认”或“EF6.x DbContext Generator”。若设置为“无”,则不会自动生成DbSet属性。
  • 验证命名空间与连接
    确认DebtCollectionBatch实体的命名空间与上下文类一致,避免因命名空间差异导致识别失败。同时再次验证连接字符串指向的数据库是否为新增表所在库。
  • 手动更新EDMX XML内容
    若图形界面刷新无效,直接打开EDMX的XML文件,检查是否包含DebtCollectionBatch的实体定义和存储模型映射。若缺失,参考现有实体的格式手动添加<EntityType>和<EntitySet>节点。

内容的提问来源于stack exchange,提问作者ErocM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:46:07