提问人:ErocM 提问时间:9/27/2023 最后编辑:QI YouErocM 更新时间:9/28/2023 访问量:60
实体表存在,但我无法通过模型访问它
Entity table exists but I cannot access it through Model
问:
我在 Visual Studio 2019 中使用 C#、.NET 4.6 和 EF 6.13。我开始遇到添加到数据库的新表的问题,然后刷新了我的模型。然后我刷新了模型。
当我在代码中访问它时,我收到以下消息:
System.InvalidOperationException:实体类型 DebtCollectionBatch 不是当前上下文模型的一部分。
在 System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType (类型 entityType) 在 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType (类型 entityType) 在 System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() 在 System.Data.Entity.Internal.Linq.InternalSet1.Add (对象实体)
在 System.Data.Entity.DbSet'1.Add(TEntity 实体) 在 SuburbanWebService.SuburbanService.SaveDebtCollectionsBatchTotal(BatchTotalDebtCollections batchTotal)
in D:\Repos\Suburban\ServiceApiRepo\SuburbanWebService\SuburbanWebService\SuburbanService.svc.cs:第 417 行1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet
1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet
我再次尝试刷新模型,在几次尝试使其正常工作失败后,我删除了该模型,保存并重新启动了 VS。这次我创造了一个全新的模型。现在,我无法在代码中访问该表,如果这有任何意义的话。
我尝试添加的代码:
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; // dt;
bt.DollarTotal = batchTotal.DollarTotal;
entity.d <-- fails here
entity.SaveChanges();
WriteLog.WriteToLogFile("SaveDebtCollectionsBatchTotal",
$"Successfully saved ach transactions for {batchTotal.CompanyCode} on {dt}. Transaction count: {batchTotal.AchCount} for ${batchTotal.DollarTotal}.");
}
return true;
}
catch (Exception ex)
{
WriteLog.WriteToLogFile("SaveDebtCollectionsBatchTotal",
$"Failed to save debt collection batch total transaction for {batchTotal.CompanyCode} on {dt}. Transaction count: {batchTotal.AchCount} for ${batchTotal.DollarTotal}. See exception log.",
ex);
return false;
}
}
我检查了连接字符串是否有重复项或它指向错误的位置,它似乎是正确的:
<connectionStrings>
<add name="SuburbanWebServiceEntities"
connectionString="***"
providerName="System.Data.EntityClient" />
</connectionStrings>`
这是我的表格:
这已经完全混淆了。我可以创建一个新的,但我不能添加它,它找不到它。DebtCollectionBatch
有什么建议吗?
答:
- 是否存在名为 DebtCollectionBatchContext.cs 的项目。检查代码是否存在:
public DbSet<DebtCollectionBatch> DebtCollectionBatch { get; set; };
2.您可以直接在 DebtCollectionsBilling.cs 的开头添加代码:
public DbSet<DebtCollectionBatch> DebtCollectionBatch { get; set; }
评论