question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support specifying catalog for table mapping

See original GitHub issue

I need to access a Table from another database located in the same server, so I did specify its location in the table name but this do not work.

The problem are the angled brackets put in the name of the table. Can I avoid inserting this brackets into the table name?

I receive this exception:

   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.<>c__DisplayClass17_0.<ExecuteReader>b__0(DbCommand cmd, IRelationalConnection con)
   at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnection connection, Func`3 action, String executeMethod, Boolean openConnection, Boolean closeConnection)
   at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection)
   at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at Microsoft.Data.Entity.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at WebApplication1.Controllers.IdentsController.Details(Nullable`1 id) in D:\git\vnext\WebApplication1\src\WebApplication1\Controllers\IdentsController.cs:line 33

Issue Analytics

  • State:open
  • Created 8 years ago
  • Reactions:22
  • Comments:14 (5 by maintainers)

github_iconTop GitHub Comments

10reactions
MaklaCofcommented, Jun 17, 2018

This would also solve problems with common (shared) tables when solving multiple tenants with Separate Database for every tenant: each tenant has it’s own database, but some tables, like users, groups, countries …, must be common (shared).

There is currently no work around.

5reactions
ajcvickerscommented, Apr 15, 2019

Possible workaround: use a DiagnosticListener to intercept commands and add the catalog where necessary.

Proof of concept: I have a server with two databases:

image

image

I now make an EF model pretending that the tables in these database are actually are in the same database:

public class DatabaseOne : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
        => optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=DatabaseOne;ConnectRetryCount=0");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TableOne>().ToTable("TableOne", "SchemaOne");
        modelBuilder.Entity<TableTwo>().ToTable("TableTwo", "SchemaTwo");
    }
}

public class TableOne
{
    public int Id { get; set; }
    public string Foo { get; set; }
}

public class TableTwo
{
    public int Id { get; set; }
    public string Foo { get; set; }
}

(Note this clearly won’t work if both database contain tables with the same table and schema name.)

Now create an interceptor-like construct using DiagnosticListener. This will do pattern matching on the SQL to find tables that are in the other databases and add the appropriate catalog.

public class CommandInterceptor : IObserver<KeyValuePair<string, object>>
{
    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(KeyValuePair<string, object> value)
    {
        if (value.Key == RelationalEventId.CommandExecuting.Name)
        {
            var command = ((CommandEventData) value.Value).Command;

            // Do command.CommandText manipulation here...
            command.CommandText = command.CommandText.Replace(
                "[SchemaTwo].[TableTwo]",
                "[DatabaseTwo].[SchemaTwo].[TableTwo]");
        }
    }
}

public class EfGlobalListener : IObserver<DiagnosticListener>
{
    private readonly CommandInterceptor _commandInterceptor = new CommandInterceptor();

    public void OnCompleted()
    {
    }

    public void OnError(Exception error)
    {
    }

    public void OnNext(DiagnosticListener listener)
    {
        if (listener.Name == DbLoggerCategory.Name)
        {
            listener.Subscribe(_commandInterceptor);
        }
    }
}

Registering and testing:

public class Program
{
    public static void Main()
    {
        DiagnosticListener.AllListeners.Subscribe(new EfGlobalListener());

        using (var context = new DatabaseOne())
        {
            foreach (var entity in context.Set<TableOne>())
            {
                Console.WriteLine($"{entity.Id}: {entity.Foo}");
            }

            foreach (var entity in context.Set<TableTwo>())
            {
                Console.WriteLine($"{entity.Id}: {entity.Foo}");
            }
        }
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Using table mapping to specify task settings
Table mapping uses several types of rules to specify the data source, source schema, data, and any transformations that should occur during the...
Read more >
Creating table catalogs
In the Table Mappings dialog, select Show user tables. The user tables that you want to save as a table catalog must be...
Read more >
Configure field mappings
Configure the CSM table maps to associate fields in order lines, domain orders, and order tasks to projects in Service Portfolio Management.
Read more >
Use Alternate Catalog Mapping (ACM) - TechDocs
You can create the alternate catalog maps for individual users or groups of users. Those users can then use the shadow tables and...
Read more >
Data mappings - Azure Data Explorer
Data mappings are used during ingestion to map incoming data to columns inside tables. Data Explorer supports different types of mappings, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found