ISqlBuilderBase.ValidateAsync(DataContext context, bool throwError = true) Method
.NET Standard 2.x
Asynchronously validates the raw SQL string for the specified database generated by the current sqlbuilder.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
Task<bool> ValidateAsync(DataContext context, bool throwError = true);
Parameters
context
SnapObjects.Data.DataContext
A DataContext
object which contains the database connection information.
throwError
System.Boolean
Optional.
True
(default ) -- to throw an exception if the raw SQL is not valid in the specified database;
False
-- Not to throw an exception if the raw SQL is not valid in the specified database.
Returns
Task<bool>
Returns a task that represents the asynchronous operation.
Examples
The following code example demonstrates how to Asynchronous validate a SqlQueryBuilder
object.
using SnapObjects.Data;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Appeon.ApiDoc.ISqlBuilderBaseExamples
{
public class ValidateAsyncExample
{
private SchoolContext _context;
public ValidateAsyncExample(SchoolContext dataContext)
{
// Sets Data Context
_context = dataContext;
}
public async void Example1()
{
// Builds a SQL statement.
var sqlBuilder = new SqlQueryBuilder();
sqlBuilder.Select("name")
.From("Department")
.WhereValue("DepartmentId", 1);
// Asynchronous validates the SQL statement in database.
bool valid = await sqlBuilder.ValidateAsync(_context);
Console.WriteLine("Validation Result (first time): {0}", valid);
Console.WriteLine(sqlBuilder.ToSqlString(_context));
// Adds a wrong search condition in the WHERE clause.
sqlBuilder.RemoveWhere();
sqlBuilder.Where("CourseId", "1");
// Validates without throwing the exception.
valid = await sqlBuilder.ValidateAsync(_context, throwError: false);
Console.WriteLine();
Console.WriteLine("Validation Result (second time): {0}", valid);
Console.WriteLine(sqlBuilder.ToSqlString(_context));
try
{
// Validates and throws the exception.
valid = await sqlBuilder.ValidateAsync(_context, throwError: true);
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("Exception Message: {0}", e.Message);
}
/*This code produces the following output:
Validation Result (first time): True
SELECT
[name]
FROM [Department]
WHERE ([DepartmentId] = 1)
Validation Result (second time): False
SELECT
[name]
FROM [Department]
WHERE ([CourseId] = 1)
Exception Message: Invalid column name 'CourseId'.
*/
}
}
}
Applies to
.NET Standard
2.x