问题描述
我使用Entity Framework和代码优先的方法。基类的DbContext有函数来创建和删除数据库以及来检查它的存在。
I'm using the Entity Framework with Code First approach. The base class DbContext has functions to create and delete the database as well as to check for its existence.
我要检查,如果一个特殊的表(实体)是现有的或不。是否有可能与框架实现或者我需要编写自定义的方法呢?如果我需要写我自己的实现,这将是最通用的方法来做到这一点?
I want to check if a special table (entity) is existing or not. Is it possible with an framework implementation or do I need to write custom methods? If I need to write my own implementation, what would be the most generic approach to do that?
感谢您的帮助。
推荐答案
如果您需要检查表的存在,你必须调用自定义的SQL代码:
If you need to check existence of the table you must call custom SQL code:
bool exists = context.Database
.SqlQuery<int?>(@"
SELECT 1 FROM sys.tables AS T
INNER JOIN sys.schemas AS S ON T.schema_id = S.schema_id
WHERE S.Name = 'SchemaName' AND T.Name = 'TableName'")
.SingleOrDefault() != null;
表名默认情况下为 DbSet 暴露在你的派生的上下文,但默认名称可以通过流畅API的
ToTable
方法或表
数据被覆盖注释。
Table name is defined by default as the name of
DbSet
exposed on your derived context but the default name can be overriden either by fluent API's ToTable
method or Table
data annotation.
在通用的方式这样做是不是在代码中第一种方法假定。这将需要浏览元数据和手工探索到哪个表是映射到的实体 - 这可以是相当复杂的,因为实体可以映射到多个表。代码先不提供访问元数据。您必须转换
的DbContext
到的ObjectContext
浏览 MetadataWorkspace
。
Doing this in the generic way is not something supposed in code first approach. That will require browsing metadata and manually explore to which table is the entity mapped - this can be pretty complex because entity can be mapped to multiple tables. Code first doesn't offer access to metadata. You must convert
DbContext
to ObjectContext
and browse MetadataWorkspace
.
编辑:
要转换
的DbContext
到的ObjectContext
使用:
ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext;
这篇关于实体框架 - 如何检查表是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!