Check if a table exists using EF Core 2.1












1















In Entity Framework the existence of a table can be checked this way:



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;


I am using EF Core 2.1 and the method SqlQuery does not exist.



What would be the right way of checking whether or not a table exists? Ideally without trying to access the table and assuming it doesn't exist if an exception is thrown.



EDIT: My final implementation



public bool TableExists(string tableName)
{
return TableExists("dbo", tableName);
}

public bool TableExists(string schema, string tableName)
{
var connection = Context.Database.GetDbConnection();

if (connection.State.Equals(ConnectionState.Closed))
connection.Open();

using (var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT 1 FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = @Schema
AND TABLE_NAME = @TableName";

var schemaParam = command.CreateParameter();
schemaParam.ParameterName = "@Schema";
schemaParam.Value = schema;
command.Parameters.Add(schemaParam);

var tableNameParam = command.CreateParameter();
tableNameParam.ParameterName = "@TableName";
tableNameParam.Value = tableName;
command.Parameters.Add(tableNameParam);

return command.ExecuteScalar() != null;
}
}









share|improve this question




















  • 1





    can you expand on is not valid?

    – JohnB
    Nov 26 '18 at 1:51











  • have you tried FromSql?

    – Kien Chu
    Nov 26 '18 at 1:55











  • Is the question about an “open query” in general, or strictly a table existence check?

    – user2864740
    Nov 26 '18 at 1:55











  • @JohnB The method doesn't exist in EF Core.

    – AndreFeijo
    Nov 26 '18 at 2:16
















1















In Entity Framework the existence of a table can be checked this way:



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;


I am using EF Core 2.1 and the method SqlQuery does not exist.



What would be the right way of checking whether or not a table exists? Ideally without trying to access the table and assuming it doesn't exist if an exception is thrown.



EDIT: My final implementation



public bool TableExists(string tableName)
{
return TableExists("dbo", tableName);
}

public bool TableExists(string schema, string tableName)
{
var connection = Context.Database.GetDbConnection();

if (connection.State.Equals(ConnectionState.Closed))
connection.Open();

using (var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT 1 FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = @Schema
AND TABLE_NAME = @TableName";

var schemaParam = command.CreateParameter();
schemaParam.ParameterName = "@Schema";
schemaParam.Value = schema;
command.Parameters.Add(schemaParam);

var tableNameParam = command.CreateParameter();
tableNameParam.ParameterName = "@TableName";
tableNameParam.Value = tableName;
command.Parameters.Add(tableNameParam);

return command.ExecuteScalar() != null;
}
}









share|improve this question




















  • 1





    can you expand on is not valid?

    – JohnB
    Nov 26 '18 at 1:51











  • have you tried FromSql?

    – Kien Chu
    Nov 26 '18 at 1:55











  • Is the question about an “open query” in general, or strictly a table existence check?

    – user2864740
    Nov 26 '18 at 1:55











  • @JohnB The method doesn't exist in EF Core.

    – AndreFeijo
    Nov 26 '18 at 2:16














1












1








1


0






In Entity Framework the existence of a table can be checked this way:



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;


I am using EF Core 2.1 and the method SqlQuery does not exist.



What would be the right way of checking whether or not a table exists? Ideally without trying to access the table and assuming it doesn't exist if an exception is thrown.



EDIT: My final implementation



public bool TableExists(string tableName)
{
return TableExists("dbo", tableName);
}

public bool TableExists(string schema, string tableName)
{
var connection = Context.Database.GetDbConnection();

if (connection.State.Equals(ConnectionState.Closed))
connection.Open();

using (var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT 1 FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = @Schema
AND TABLE_NAME = @TableName";

var schemaParam = command.CreateParameter();
schemaParam.ParameterName = "@Schema";
schemaParam.Value = schema;
command.Parameters.Add(schemaParam);

var tableNameParam = command.CreateParameter();
tableNameParam.ParameterName = "@TableName";
tableNameParam.Value = tableName;
command.Parameters.Add(tableNameParam);

return command.ExecuteScalar() != null;
}
}









share|improve this question
















In Entity Framework the existence of a table can be checked this way:



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;


I am using EF Core 2.1 and the method SqlQuery does not exist.



What would be the right way of checking whether or not a table exists? Ideally without trying to access the table and assuming it doesn't exist if an exception is thrown.



EDIT: My final implementation



public bool TableExists(string tableName)
{
return TableExists("dbo", tableName);
}

public bool TableExists(string schema, string tableName)
{
var connection = Context.Database.GetDbConnection();

if (connection.State.Equals(ConnectionState.Closed))
connection.Open();

using (var command = connection.CreateCommand())
{
command.CommandText = @"
SELECT 1 FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = @Schema
AND TABLE_NAME = @TableName";

var schemaParam = command.CreateParameter();
schemaParam.ParameterName = "@Schema";
schemaParam.Value = schema;
command.Parameters.Add(schemaParam);

var tableNameParam = command.CreateParameter();
tableNameParam.ParameterName = "@TableName";
tableNameParam.Value = tableName;
command.Parameters.Add(tableNameParam);

return command.ExecuteScalar() != null;
}
}






c# entity-framework entity-framework-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 20:23







AndreFeijo

















asked Nov 26 '18 at 1:39









AndreFeijoAndreFeijo

4,18831436




4,18831436








  • 1





    can you expand on is not valid?

    – JohnB
    Nov 26 '18 at 1:51











  • have you tried FromSql?

    – Kien Chu
    Nov 26 '18 at 1:55











  • Is the question about an “open query” in general, or strictly a table existence check?

    – user2864740
    Nov 26 '18 at 1:55











  • @JohnB The method doesn't exist in EF Core.

    – AndreFeijo
    Nov 26 '18 at 2:16














  • 1





    can you expand on is not valid?

    – JohnB
    Nov 26 '18 at 1:51











  • have you tried FromSql?

    – Kien Chu
    Nov 26 '18 at 1:55











  • Is the question about an “open query” in general, or strictly a table existence check?

    – user2864740
    Nov 26 '18 at 1:55











  • @JohnB The method doesn't exist in EF Core.

    – AndreFeijo
    Nov 26 '18 at 2:16








1




1





can you expand on is not valid?

– JohnB
Nov 26 '18 at 1:51





can you expand on is not valid?

– JohnB
Nov 26 '18 at 1:51













have you tried FromSql?

– Kien Chu
Nov 26 '18 at 1:55





have you tried FromSql?

– Kien Chu
Nov 26 '18 at 1:55













Is the question about an “open query” in general, or strictly a table existence check?

– user2864740
Nov 26 '18 at 1:55





Is the question about an “open query” in general, or strictly a table existence check?

– user2864740
Nov 26 '18 at 1:55













@JohnB The method doesn't exist in EF Core.

– AndreFeijo
Nov 26 '18 at 2:16





@JohnB The method doesn't exist in EF Core.

– AndreFeijo
Nov 26 '18 at 2:16












1 Answer
1






active

oldest

votes


















6














There is ExecuteSqlCommand.



context.Database.ExecuteSqlCommand("...")


However, it's limited to returning an integer indicating how many rows were affected. No rows get affected if you're doing a SELECT, so it doesn't really work for what you want.



There is also FromSql, but that only works on tables, not at the database level:



context.TableName.FromSql("SELECT ...")


For what you're doing, a better option is to get the DbConnection from EF, and create your own DbCommand. This returns what you would expect:



var conn = context.Database.GetDbConnection();
if (conn.State.Equals(ConnectionState.Closed)) await conn.OpenAsync();
using (var command = conn.CreateCommand()) {
command.CommandText = @"
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'";
var exists = await command.ExecuteScalarAsync() != null;
}


A word of warning here: Don't put the DbConnection you get from GetDbConnection() in a using statement, or close it when you're done. That connection is used for the life of that DbContext instance. So if you close it, any later requests made by EF will fail. It's also possible that it was already opened before your code, which is why I put a test in there to see if it's closed before calling OpenAsync().






share|improve this answer


























  • How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

    – AndreFeijo
    Nov 26 '18 at 2:19











  • You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

    – Gabriel Luci
    Nov 26 '18 at 3:09













  • Is ExecuteSqlCommand not working for you?

    – Gabriel Luci
    Nov 26 '18 at 3:10






  • 1





    Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

    – Gabriel Luci
    Nov 26 '18 at 13:20






  • 1





    Thanks Gabriel, I've also edited my question with my final implementation.

    – AndreFeijo
    Nov 26 '18 at 20:24











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473747%2fcheck-if-a-table-exists-using-ef-core-2-1%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









6














There is ExecuteSqlCommand.



context.Database.ExecuteSqlCommand("...")


However, it's limited to returning an integer indicating how many rows were affected. No rows get affected if you're doing a SELECT, so it doesn't really work for what you want.



There is also FromSql, but that only works on tables, not at the database level:



context.TableName.FromSql("SELECT ...")


For what you're doing, a better option is to get the DbConnection from EF, and create your own DbCommand. This returns what you would expect:



var conn = context.Database.GetDbConnection();
if (conn.State.Equals(ConnectionState.Closed)) await conn.OpenAsync();
using (var command = conn.CreateCommand()) {
command.CommandText = @"
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'";
var exists = await command.ExecuteScalarAsync() != null;
}


A word of warning here: Don't put the DbConnection you get from GetDbConnection() in a using statement, or close it when you're done. That connection is used for the life of that DbContext instance. So if you close it, any later requests made by EF will fail. It's also possible that it was already opened before your code, which is why I put a test in there to see if it's closed before calling OpenAsync().






share|improve this answer


























  • How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

    – AndreFeijo
    Nov 26 '18 at 2:19











  • You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

    – Gabriel Luci
    Nov 26 '18 at 3:09













  • Is ExecuteSqlCommand not working for you?

    – Gabriel Luci
    Nov 26 '18 at 3:10






  • 1





    Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

    – Gabriel Luci
    Nov 26 '18 at 13:20






  • 1





    Thanks Gabriel, I've also edited my question with my final implementation.

    – AndreFeijo
    Nov 26 '18 at 20:24
















6














There is ExecuteSqlCommand.



context.Database.ExecuteSqlCommand("...")


However, it's limited to returning an integer indicating how many rows were affected. No rows get affected if you're doing a SELECT, so it doesn't really work for what you want.



There is also FromSql, but that only works on tables, not at the database level:



context.TableName.FromSql("SELECT ...")


For what you're doing, a better option is to get the DbConnection from EF, and create your own DbCommand. This returns what you would expect:



var conn = context.Database.GetDbConnection();
if (conn.State.Equals(ConnectionState.Closed)) await conn.OpenAsync();
using (var command = conn.CreateCommand()) {
command.CommandText = @"
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'";
var exists = await command.ExecuteScalarAsync() != null;
}


A word of warning here: Don't put the DbConnection you get from GetDbConnection() in a using statement, or close it when you're done. That connection is used for the life of that DbContext instance. So if you close it, any later requests made by EF will fail. It's also possible that it was already opened before your code, which is why I put a test in there to see if it's closed before calling OpenAsync().






share|improve this answer


























  • How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

    – AndreFeijo
    Nov 26 '18 at 2:19











  • You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

    – Gabriel Luci
    Nov 26 '18 at 3:09













  • Is ExecuteSqlCommand not working for you?

    – Gabriel Luci
    Nov 26 '18 at 3:10






  • 1





    Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

    – Gabriel Luci
    Nov 26 '18 at 13:20






  • 1





    Thanks Gabriel, I've also edited my question with my final implementation.

    – AndreFeijo
    Nov 26 '18 at 20:24














6












6








6







There is ExecuteSqlCommand.



context.Database.ExecuteSqlCommand("...")


However, it's limited to returning an integer indicating how many rows were affected. No rows get affected if you're doing a SELECT, so it doesn't really work for what you want.



There is also FromSql, but that only works on tables, not at the database level:



context.TableName.FromSql("SELECT ...")


For what you're doing, a better option is to get the DbConnection from EF, and create your own DbCommand. This returns what you would expect:



var conn = context.Database.GetDbConnection();
if (conn.State.Equals(ConnectionState.Closed)) await conn.OpenAsync();
using (var command = conn.CreateCommand()) {
command.CommandText = @"
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'";
var exists = await command.ExecuteScalarAsync() != null;
}


A word of warning here: Don't put the DbConnection you get from GetDbConnection() in a using statement, or close it when you're done. That connection is used for the life of that DbContext instance. So if you close it, any later requests made by EF will fail. It's also possible that it was already opened before your code, which is why I put a test in there to see if it's closed before calling OpenAsync().






share|improve this answer















There is ExecuteSqlCommand.



context.Database.ExecuteSqlCommand("...")


However, it's limited to returning an integer indicating how many rows were affected. No rows get affected if you're doing a SELECT, so it doesn't really work for what you want.



There is also FromSql, but that only works on tables, not at the database level:



context.TableName.FromSql("SELECT ...")


For what you're doing, a better option is to get the DbConnection from EF, and create your own DbCommand. This returns what you would expect:



var conn = context.Database.GetDbConnection();
if (conn.State.Equals(ConnectionState.Closed)) await conn.OpenAsync();
using (var command = conn.CreateCommand()) {
command.CommandText = @"
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'";
var exists = await command.ExecuteScalarAsync() != null;
}


A word of warning here: Don't put the DbConnection you get from GetDbConnection() in a using statement, or close it when you're done. That connection is used for the life of that DbContext instance. So if you close it, any later requests made by EF will fail. It's also possible that it was already opened before your code, which is why I put a test in there to see if it's closed before calling OpenAsync().







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 26 '18 at 13:20

























answered Nov 26 '18 at 1:59









Gabriel LuciGabriel Luci

10.8k11424




10.8k11424













  • How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

    – AndreFeijo
    Nov 26 '18 at 2:19











  • You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

    – Gabriel Luci
    Nov 26 '18 at 3:09













  • Is ExecuteSqlCommand not working for you?

    – Gabriel Luci
    Nov 26 '18 at 3:10






  • 1





    Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

    – Gabriel Luci
    Nov 26 '18 at 13:20






  • 1





    Thanks Gabriel, I've also edited my question with my final implementation.

    – AndreFeijo
    Nov 26 '18 at 20:24



















  • How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

    – AndreFeijo
    Nov 26 '18 at 2:19











  • You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

    – Gabriel Luci
    Nov 26 '18 at 3:09













  • Is ExecuteSqlCommand not working for you?

    – Gabriel Luci
    Nov 26 '18 at 3:10






  • 1





    Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

    – Gabriel Luci
    Nov 26 '18 at 13:20






  • 1





    Thanks Gabriel, I've also edited my question with my final implementation.

    – AndreFeijo
    Nov 26 '18 at 20:24

















How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

– AndreFeijo
Nov 26 '18 at 2:19





How can I check if the table exists using FromSql? As far as I know it needs an entity to map to, so would I need to build a Dto for Information Schema?

– AndreFeijo
Nov 26 '18 at 2:19













You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

– Gabriel Luci
Nov 26 '18 at 3:09







You need to know the table already to use FromSql, so I don't think you can use it to determine if a table exists.

– Gabriel Luci
Nov 26 '18 at 3:09















Is ExecuteSqlCommand not working for you?

– Gabriel Luci
Nov 26 '18 at 3:10





Is ExecuteSqlCommand not working for you?

– Gabriel Luci
Nov 26 '18 at 3:10




1




1





Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

– Gabriel Luci
Nov 26 '18 at 13:20





Now that I'm back in the office, I could do some testing. I found another way. I've updated my answer.

– Gabriel Luci
Nov 26 '18 at 13:20




1




1





Thanks Gabriel, I've also edited my question with my final implementation.

– AndreFeijo
Nov 26 '18 at 20:24





Thanks Gabriel, I've also edited my question with my final implementation.

– AndreFeijo
Nov 26 '18 at 20:24


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53473747%2fcheck-if-a-table-exists-using-ef-core-2-1%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)