SQLClientCoreTool

Alejandro Cernuda



Introducing a simple tool for interaction between .Net Core applications and Microsoft SQL Server. Ideal for small projects, where you do not need, or want, to use any of the common ways to access data today. It also has some methods that in practice consume a lot of development time.



DataGather Class

It is the entity that carries the weight of almost all the work. It deals with managing the connection with the database and has methods for the main operations. Each time it is to be used, the GetIntance() method is called. This is what happens then.

publicsealedclassDataGather

{

...

privatestatic Lazy<DataGather> instance = new Lazy<DataGath er>(() => new DataGather());

 

publicstatic DataGather GetInstance( string connectionString, string dataBaseName = "")

    {

bool haveOldInstanceWithDifferentConnection = Builder != null && (Builder.ConnectionString != connectionString || instance.Value.ConnectionString != connectionString);

        Builder = new SqlConnectionStringBuilder(connectionString);

if (!string .IsNullOrWhiteSpace(dataBaseName) || haveOldInstanceWithDifferentConnection)

        {

            Builder.InitialCatalog = !string .IsNullOrWhiteSpace(dataBaseName) ? dataBaseName : Builder.InitialCatalog;

returnnew DataGather();

        }

return instance.Value;

}

...

}

Example of use

We can change the connection, both to the database and to the server. In the following example we connect to the server "Local1"

privatestringConnectionString { get { returnTestCases.ConnectionString; } }

publicvoidChangeServerToLocal1()

{

    DataGather dg = DataGather.GetInstance(ConnectionString);

string serverName =Check.GetCurrentServer(dg);

    dg =DataGather.GetInstance(ConnectionString.Replace(serverName, "local1"));

}

SQLClientCoreTool allows us to easily store any document, image, pdf, etc. in the SQL database. We use the Transformer. CreateBlobFileAsync(string path) to convert the file into a byte[] which we will later store in a column of type varbinary(max). Here is the example.

 

publicasyncTask TestCreateBlobFileAsync(string path)

{

           BlobFile blobFile = await Transformer.CreateBlobFileAsync(path);

 

            ValueTest valueTest = newValueTest();

            valueTest.Name = blobFile.Name;

            valueTest.GuidId = newGuid();

            valueTest.Photo = blobFile.FileData;

            valueTest.Total = -1;

 

            DataGather dg = DataGather.GetInstance(ConnectionString);

 

int result = awaitdg.InsertAsync(valueTest);