gpt4 book ai didi

entity-framework - 如何检查模型中是否存在 DbContext.Set

转载 作者:行者123 更新时间:2023-12-04 17:54:30 25 4
gpt4 key购买 nike

我有一种情况,我可能正在使用多个 DbContext,这些 DbContext 可能包含也可能不包含 SomeEntity 的 DbSet。

自然,如果我触发 SaveChanges 并且此实体不存在,则会发生以下错误:

The entity type SomeEntity is not part of the model for the current context.



如何检查模型中是否存在实体或实体集,如果不存在,如何将有问题的代码段短路?

理查德

最佳答案

当您调用 Set<NotMappedEntityType> 时,应立即抛出异常。所以最简单的方法是捕获异常并根据需要处理它。

复杂的解决方案要求您浏览映射元数据并搜索必须与 CLR 类型同名的映射实体类型。您可以在派生的上下文类中添加此方法以检查实体类型是否存在:

public bool Exists<TEntity>() where TEntity : class
{
string entityName = typeof(TEntity).Name;
ObjectContext objContext = ((IObjectContextAdapter)this).ObjectContext;
MetadataWorkspace workspace = objContext.MetadataWorkspace;
return workspace.GetItems<EntityType>(DataSpace.CSpace).Any(e => e.Name == entityName);
}

关于entity-framework - 如何检查模型中是否存在 DbContext.Set<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10749307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com