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.

The multi-part identifier could not be bound error when trying to sync with filters

See original GitHub issue

I am trying to sync an mssql database with my xamarin android app’s sqlite database using web proxy. I want to synchronize only the data of a specific customer, for this I created three filters on the Customer, Invoice, InvoiceItem tables based on the CustomerId field. But the sync method gives this error:

The multi-part identifier "Invoice.CustomerId" could not be bound.
-----------------------
   at Dotmim.Sync.BaseOrchestrator.RaiseError(Exception exception)
   at Dotmim.Sync.BaseOrchestrator.RunInTransactionAsync[T](SyncStage stage, Func`4 actionTask, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken)
   at Dotmim.Sync.BaseOrchestrator.RunInTransactionAsync[T](SyncStage stage, Func`4 actionTask, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken)
   at Dotmim.Sync.Web.Server.WebServerOrchestrator.EnsureSchemaAsync(HttpContext httpContext, HttpMessageEnsureScopesRequest httpMessage, SessionCache sessionCache, CancellationToken cancellationToken, IProgress`1 progress)
   at Dotmim.Sync.Web.Server.WebServerOrchestrator.HandleRequestAsync(HttpContext httpContext, Action`1 action, CancellationToken cancellationToken, IProgress`1 progress)
-----------------------
-----------------------
INNER EXCEPTION
-----------------------
The multi-part identifier "Invoice.CustomerId" could not be bound.
-----------------------
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at Dotmim.Sync.BaseOrchestrator.InternalCreateStoredProcedureAsync(SyncContext ctx, DbTableBuilder tableBuilder, DbStoredProcedureType storedProcedureType, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken, IProgress`1 progress)
   at Dotmim.Sync.BaseOrchestrator.InternalCreateStoredProceduresAsync(SyncContext ctx, Boolean overwrite, DbTableBuilder tableBuilder, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken, IProgress`1 progress)
   at Dotmim.Sync.BaseOrchestrator.InternalMigrationAsync(SyncContext context, SyncSet schema, SyncSetup oldSetup, SyncSetup newSetup, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken, IProgress`1 progress)
   at Dotmim.Sync.RemoteOrchestrator.<>c__DisplayClass3_0.<<EnsureSchemaAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Dotmim.Sync.BaseOrchestrator.RunInTransactionAsync[T](SyncStage stage, Func`4 actionTask, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken)
-----------------------

The stack trace:

  at Dotmim.Sync.Web.Client.HttpRequestHandler.HandleSyncError (System.Net.Http.HttpResponseMessage response) [0x002b2] in <55a6ba406ad4451d837e2d32b183ba62>:0 
  at Dotmim.Sync.Web.Client.HttpRequestHandler.SendAsync (System.Net.Http.HttpClient client, System.String requestUri, System.String sessionId, System.String scopeName, Dotmim.Sync.Web.Client.HttpStep step, System.Byte[] data, System.String ser, Dotmim.Sync.Serialization.IConverter converter, System.String hashString, System.String contentType, System.Threading.CancellationToken cancellationToken) [0x0036e] in <55a6ba406ad4451d837e2d32b183ba62>:0 
  at Dotmim.Sync.SyncPolicy.InternalExecuteAsync[TResult] (System.Func`1[TResult] operation, System.Threading.CancellationToken cancellationToken, System.Object arg) [0x00103] in <41fc39d200444af2a919390a606774d3>:0 
  at Dotmim.Sync.Web.Client.HttpRequestHandler.ProcessRequestAsync (System.Net.Http.HttpClient client, System.String baseUri, System.Byte[] data, Dotmim.Sync.Web.Client.HttpStep step, System.Guid sessionId, System.String scopeName, Dotmim.Sync.Serialization.ISerializerFactory serializerFactory, Dotmim.Sync.Serialization.IConverter converter, System.Int32 batchSize, Dotmim.Sync.SyncPolicy policy, System.Threading.CancellationToken cancellationToken, System.IProgress`1[T] progress) [0x0037c] in <55a6ba406ad4451d837e2d32b183ba62>:0 
  at Dotmim.Sync.Web.Client.WebClientOrchestrator.EnsureSchemaAsync (System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, System.Threading.CancellationToken cancellationToken, System.IProgress`1[T] progress) [0x0023c] in <55a6ba406ad4451d837e2d32b183ba62>:0 
  at Dotmim.Sync.SyncAgent+<>c__DisplayClass53_0.<SynchronizeAsync>b__0 () [0x00df7] in <41fc39d200444af2a919390a606774d3>:0 
  at Dotmim.Sync.SyncAgent.SynchronizeAsync (Dotmim.Sync.Enumerations.SyncType syncType, System.Threading.CancellationToken cancellationToken, System.IProgress`1[T] progress) [0x00185] in <41fc39d200444af2a919390a606774d3>:0 
  at MediaStore.DatabaseHelper.SyncDatabase (System.String connString, Android.Content.Context context, System.Int32 custId) [0x000de] in C:\_Menci\7.felev\szakdoga\dotmim\MediaStore\DatabaseHelper.cs:53 

My schema schema

The web server code:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDistributedMemoryCache();
            services.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(30));

            var connectionString = Configuration.GetSection("ConnectionStrings")["SqlConnection"];

            var options = new SyncOptions
            {
                SnapshotsDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "Snapshots"),
                BatchSize = 2000,
            };

            var tables = new string[] { "media.Album", "media.Artist", "media.Customer", "media.Invoice", "media.InvoiceItem", "media.Track" };

            var setup = new SyncSetup(tables);

            var customerFilter = new SetupFilter("Customer", "media");
            customerFilter.AddParameter("CustomerId", "Customer", "media", false);
            customerFilter.AddWhere("CustomerId", "Customer", "CustomerId", "media");
            setup.Filters.Add(customerFilter);

            var invoiceCustomerFilter = new SetupFilter("Invoice", "media");
            invoiceCustomerFilter.AddParameter("CustomerId", "Customer", "media", false);
            invoiceCustomerFilter.AddJoin(Join.Inner, "Customer").On("Invoice", "CustomerId", "Customer", "CustomerId");
            invoiceCustomerFilter.AddWhere("CustomerId", "Customer", "CustomerId", "media");
            setup.Filters.Add(invoiceCustomerFilter);

            var invoiceItemCustomerFilter = new SetupFilter("InvoiceItem", "media");
            invoiceItemCustomerFilter.AddParameter("CustomerId", "Customer", "media", false);
            invoiceItemCustomerFilter.AddJoin(Join.Inner, "Invoice").On("InvoiceItem", "InvoiceId", "Invoice", "InvoiceId");
            invoiceItemCustomerFilter.AddJoin(Join.Inner, "Customer").On("Invoice", "CustomerId", "Customer", "CustomerId");
            invoiceCustomerFilter.AddWhere("CustomerId", "Customer", "CustomerId", "media");
            setup.Filters.Add(invoiceItemCustomerFilter);

            services.AddSyncServer<SqlSyncChangeTrackingProvider>(connectionString, setup, options);
        }

The client side:

var handler = HttpClientHandlerService.GetInsecureHandler();

            HttpClient httpClient = new HttpClient(handler);
            httpClient.DefaultRequestHeaders.Host = $"localhost:44302";   

            var serverOrchestrator = new WebClientOrchestrator("https://10.0.2.2:44302/api/sync", client: httpClient); 

            var clientProvider = new SqliteSyncProvider(connString);

            var agent = new SyncAgent(clientProvider, serverOrchestrator);

            if (!agent.Parameters.Contains("CustomerId"))
            {
                agent.Parameters.Add("CustomerId", custId);
            }

            try
            {
                var result = await agent.SynchronizeAsync();

                var output = result.ToString();
                output = output.Replace("\n", " ").Replace("\t", " ").Replace("\r", " ");
                Toast.MakeText(context, output, ToastLength.Long).Show();
            }
            catch (Exception e)
            {
                Toast.MakeText(context, e.Message, ToastLength.Long).Show();
            }

The sync worked before the filters, so the problem is there, but I don’t understand why doesn’t is recognize the Invoice.CustomerId column. Let me know what further information should I supply to solve this. Thanks.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
Mimetiscommented, Nov 25, 2021

The last version set DisableConstraintsOnApplyChanges to false by default.

And yes, order is important

  • The order of your tables is used for Insert / update
  • Reverse order is used for deleting

In your case, I guess Artist should be before Album in your tables array, just because you can’t create an album if you don’t have an artist created before.

So, you can use DisableConstraintsOnApplyChanges if you’re not sure of your tables order (or if you have any circular references) Or you can use a good table orders to prevent using this property (that could be potentially slower because it requires to lock the entire table)

0reactions
Menci77commented, Nov 24, 2021

Thanks, it’s working now! So you mean here var tables = new string[] { "media.Album", "media.Artist", "media.Customer", "media.Invoice", "media.InvoiceItem", "media.Track" }; the order of the table names matter? Although, can I ask the DisableConstraintsOnApplyChanges option’s default value is true, so why do I have to specify it? image

Read more comments on GitHub >

github_iconTop Results From Across the Web

The multi-part identifier could not be bound - sql
Sometimes this error occurs when you use your schema (dbo) in your query in a wrong way. for example if you write: select...
Read more >
The Multi Part Identifier Could Not Be Bound: Causes and ...
The multi part identifier could not be bound is an SQL error that usually indicates that you are prefixing one or several columns...
Read more >
Fixing the error: The multi-part identifier ... could not be ...
The main reason for this error is that the source table cannot be found, for example if you have statement such as Table1.OrderDate,...
Read more >
The multi-part identifier "xxx" could not be bound
Reformatting your code shows the problem. All I have changed is whitespace and added a comment: HAVING ( SELECT COUNT(*) FROM ( SELECT ......
Read more >
multi-part identifier "USERINFO.DEPARTMENT" could not ...
Hello. I have a migration from sqlserver to sfdc. My source is two tables - Account and UserInfo - the Account Owner joins...
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