Search code examples
c#entity-framework-coreentity.net-6.0

How to tell if a DbContext entity is a table or a view?


I need to process an operation on all the tables in the database, to do this I need to be able to separate the tables from the views.

I am currently using the following code to fast fail my foreach loop on the tables if the current entity is a view. This approach is not finding all of the views:

var views = dbContext.Model
                     .GetEntityTypes()
                     .Where(e => e.ClrType.Name.Contains("View"))
                     .ToList();

if (views.Any(v => v.GetTableName() == currentTableName))
{ 
    return $"N, Is View.";
}

Solution

  • I was able to fix the issue by replacing my code the following:

    if (!string.IsNullOrWhiteSpace(entityType.GetViewName()))
    {
        return $"N, Is View.";
    }