如何检查DbContext.Set< T>模型中存在吗? [英] How to check whether DbContext.Set<T> exists in model?

查看:74
本文介绍了如何检查DbContext.Set< T>模型中存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况是我可能正在使用多个DbContext,这些DbContext可能包含或不包含SomeEntity的DbSet。

I have a situation where I may be working with multiple DbContexts that may or may not contain a DbSet of SomeEntity.

自然,如果我启动SaveChanges且实体不存在,将发生以下错误:

Naturally, if I fire off SaveChanges and this entity is not present, the following error will occur:


实体类型SomeEntity不是当前
模型的一部分

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

如何检查模型中是否存在实体或实体集,如果存在,请短路代码中的有问题的部分

How can I check whether the entity or entity set exists in a model and short-circuit the offending bit of code if it does not?

理查德

推荐答案

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

The exception should be thrown immediately when you call Set<NotMappedEntityType> so the simplest way is to catch the exception and handle it as you need.

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

The complex solution requires you to browse mapping metadata and search for your mapped entity type which must have the same name as your CLR type. You can add this method in your derived context class to check existence of the entity type:

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);
}

这篇关于如何检查DbContext.Set&lt; T&gt;模型中存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆