Skip to content

Commit

Permalink
SqlDb v1.0.0.155 - BulkInsert: added support to DbFieldAttribute
Browse files Browse the repository at this point in the history
  • Loading branch information
acattaneo-bitagora committed Mar 6, 2023
1 parent 7dc7b90 commit 934646f
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 12 deletions.
4 changes: 2 additions & 2 deletions ACUtils.SqlDb.Utils/ACUtils.SqlDb.Utils.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
<Authors>Andrea Cattaneo</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Version>1.0.0.147</Version>
<PackageVersion>1.0.0.147</PackageVersion>
<Version>1.0.0.148</Version>
<PackageVersion>1.0.0.148</PackageVersion>
<Description>Utilities per gestione DataTable</Description>
<NeutralLanguage>it</NeutralLanguage>
<IncludeSymbols>true</IncludeSymbols>
Expand Down
10 changes: 9 additions & 1 deletion ACUtils.SqlDb.Utils/DBModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public Q GetValueByDbAttribute<Q>(string field)
{
return GetValueBy<Q>(field, property => GetDbAttribute(property.Name)?.DbField);
}

public object this[string fieldName]
{
get
Expand Down Expand Up @@ -297,6 +297,14 @@ public IDbFieldAttribute GetDbAttribute(string propertyName)
return attrs.LastOrDefault() as IDbFieldAttribute;
}

public static IDbFieldAttribute GetDbAttribute<T>(string propertyName)
{
var type = typeof(T);
var propr = type.GetProperty(propertyName);
var attrs = propr?.GetCustomAttributes(typeof(IDbFieldAttribute), true);
return attrs?.LastOrDefault() as IDbFieldAttribute;
}

}


Expand Down
4 changes: 2 additions & 2 deletions ACUtils.SqlDb/ACUtils.SqlDb.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<Authors>Andrea Cattaneo</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Version>1.0.0.154</Version>
<PackageVersion>1.0.0.154</PackageVersion>
<Version>1.0.0.155</Version>
<PackageVersion>1.0.0.155</PackageVersion>
<Description>Utility per interrogazione database MSSQL</Description>
<NeutralLanguage>it</NeutralLanguage>
<IncludeSymbols>true</IncludeSymbols>
Expand Down
2 changes: 1 addition & 1 deletion ACUtils.SqlDb/SqlDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public static DataTable ToDataTable<T>(IEnumerable<T> l_oItems)
int i;

//#### Collect the a_oProperties for the passed T
System.Reflection.PropertyInfo[] a_oProperties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
System.Reflection.PropertyInfo[] a_oProperties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(p => p.CanRead && !p.DeclaringType.IsConstructedGenericType).ToArray();

//#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
//#### NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
Expand Down
7 changes: 5 additions & 2 deletions ACUtils.SqlDb/SqlDb_BulkInsert.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace ACUtils
{
Expand All @@ -16,6 +17,7 @@ public static void BulkInsert<T>(this SqlDb self, string tablename, IEnumerable<
}
}
}

public static async System.Threading.Tasks.Task BulkInsertAsync<T>(this SqlDb self, string tablename, IEnumerable<T> records)
{
using (var connection = await self._getConnectionAsync())
Expand All @@ -30,10 +32,11 @@ public static async System.Threading.Tasks.Task BulkInsertAsync<T>(this SqlDb se
internal static DataTable BulkInsertPrepare<T>(this SqlDb self, SqlBulkCopy bc, string tablename, IEnumerable<T> records)
{
bc.DestinationTableName = tablename;
var properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
var properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(p => p.CanRead && !p.DeclaringType.IsConstructedGenericType);
foreach (var property in properties)
{
bc.ColumnMappings.Add(property.Name, property.Name);
var attr = DBModel.GetDbAttribute<T>(propertyName: property.Name);
bc.ColumnMappings.Add(property.Name, attr?.DbField ?? property.Name);
}
return SqlDb.ToDataTable(records);
}
Expand Down
55 changes: 53 additions & 2 deletions Tests/SqlDbTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;

Expand Down Expand Up @@ -156,9 +157,10 @@ public void TestQueryDictionary()
}


class DbPerson: ACUtils.DBModel<DbPerson>
class DbPerson : ACUtils.DBModel<DbPerson>
{
public int BusinessEntityID { get; set; }
[DbField("BusinessEntityID")]
public int Id { get; set; }
public string PersonType { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
Expand All @@ -175,5 +177,54 @@ public void TestQueryMany()
Assert.AreEqual(count, allPersons.ToList().Count);
}



[TestCase(100, false)]
[TestCase(100, true)]
public void TestBulkInsert(int rows, bool async)
{
// prepare
var nextId = db.QuerySingleValue<int>("SELECT MAX(BusinessEntityID) + 1 FROM Person.Person");
var initialCount = db.QuerySingleValue<int>("SELECT COUNT(*) FROM Person.Person");
var objects = new List<DbPerson>();
for (int i = nextId; i < (nextId + rows); i++)
{
objects.Add(new DbPerson()
{
Id = i,
PersonType = "EM",
Title = "Test",
FirstName = $"FirstName {i}",
MiddleName = $"MiddleName {i}",
LastName = $"LastName {i}",
});
}

// execute
if (async)
{
db.BulkInsertAsync("Person.Person", objects).Wait();
}
else
{
db.BulkInsert("Person.Person", objects);
}

// test
var finalCount = db.QuerySingleValue<int>("SELECT COUNT(*) FROM Person.Person");
Assert.AreEqual(initialCount + rows, finalCount);

foreach (var person in objects)
{
Assert.IsTrue(person.Id > 0);
var dr = db.QueryDataRow("SELECT * FROM Person.Person WHERE BusinessEntityID = @ID", "@ID".WithValue(person.Id));
Assert.AreEqual(person.Id, dr.Field<int>("BusinessEntityID"));
Assert.AreEqual(person.PersonType, dr.Field<string>("PersonType"));
Assert.AreEqual(person.Title, dr.Field<string>("Title"));
Assert.AreEqual(person.FirstName, dr.Field<string>("FirstName"));
Assert.AreEqual(person.MiddleName, dr.Field<string>("MiddleName"));
Assert.AreEqual(person.LastName, dr.Field<string>("LastName"));
}
}
}
}
32 changes: 30 additions & 2 deletions Tests/SqlDbUtilsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@ public class TestDbModel : DBModel<TestDbModel>
public int? nullableIntValue { get; set; }
public int intValue { get; set; }
public decimal decimalValue { get; set; }
[DbField("DB_FILE_NAME_FLOAT")]
public float floatValue { get; set; }
public DateTime datetimeValue { get; set; }

}

internal class TestGetDbAttributeClass: DBModel
{
public decimal decimalValue { get; set; }
[DbField("DB_FILE_NAME_FLOAT")]
public float floatValue { get; set; }
public DateTime datetimeValue { get; set; }
}

[TestFixture]
class SqlDbUtilsTest
{
Expand All @@ -41,15 +50,15 @@ void _generateDt()
_testDt.Columns.Add("stringValue", typeof(string));
_testDt.Columns.Add("intValue", typeof(int));
_testDt.Columns.Add("decimalValue", typeof(decimal));
_testDt.Columns.Add("floatValue", typeof(float));
_testDt.Columns.Add("DB_FILE_NAME_FLOAT", typeof(float));
_testDt.Columns.Add("datetimeValue", typeof(DateTime));
for (int i = 0; i < DT_SIZE; i++)
{
var dr = _testDt.NewRow();
dr["stringValue"] = i.ToString();
dr["intValue"] = i;
dr["decimalValue"] = new Decimal(i / 2);
dr["floatValue"] = (float)i / 2;
dr["DB_FILE_NAME_FLOAT"] = (float)i / 2;
dr["datetimeValue"] = DateTime.Now;
_testDt.Rows.Add(dr);
}
Expand Down Expand Up @@ -79,6 +88,25 @@ public void testIdrateObj()
}
}


[Test]
public void testGetDbAttribute()
{
Assert.AreEqual("DB_FILE_NAME_FLOAT", DBModel.GetDbAttribute<TestDbModel>("floatValue").DbField);
Assert.AreEqual("DB_FILE_NAME_FLOAT", DBModel.GetDbAttribute<TestGetDbAttributeClass>("floatValue").DbField);

var model = new TestDbModel();
Assert.AreEqual("DB_FILE_NAME_FLOAT", model.GetDbAttribute("floatValue").DbField);

var model2 = new TestGetDbAttributeClass();
Assert.AreEqual("DB_FILE_NAME_FLOAT", model2.GetDbAttribute("floatValue").DbField);


Assert.IsNull(DBModel.GetDbAttribute<TestDbModel>("stringValue"));

Assert.IsNull(DBModel.GetDbAttribute<TestDbModel>("not exists property"));
}

[Test]
public void testStaticIdrate()
{
Expand Down

0 comments on commit 934646f

Please sign in to comment.