Created
May 18, 2017 15:18
-
-
Save yngwie74/b3ca10611bd19dfcd4731cbd8c65dcfb to your computer and use it in GitHub Desktop.
Linq2ADO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ACV.Common.DB | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.Common; | |
public static class SqlExtensions | |
{ | |
private static object GetOrDefault(this IDataRecord record, string columnName, object @default = null) | |
{ | |
var value = record[columnName]; | |
return value == null || value is DBNull ? @default : value; | |
} | |
public static T GetOrDefault<T>(this IDataRecord record, string columnName, T @default = default(T)) | |
{ | |
var value = GetOrDefault(record, columnName, (object)@default); | |
return (T)Convert.ChangeType(value, typeof(T)); | |
} | |
public static T ParseOrDefault<T>(this IDataRecord record, string columnName, Func<string, T> convertFunc, T @default = default(T)) | |
{ | |
var value = GetOrDefault(record, columnName, (object)@default); | |
if (value is T) return (T)value; | |
return value == null ? @default : convertFunc.Invoke(value.ToString()); | |
} | |
public static IEnumerable<IDataRecord> ToEnumerable(this DbDataReader reader) | |
{ | |
for (var enumerator = reader.GetEnumerator(); enumerator.MoveNext();) | |
{ | |
yield return (IDataRecord)enumerator.Current; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ACV.SampleClient | |
{ | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.SqlClient; | |
using ACV.Common.DB; | |
public class Client | |
{ | |
public IList<Currency> GetCurrenciesByCode(string code) | |
{ | |
code = NormalizeStringCode(code); | |
using (var connection = OpenConnection()) | |
using (var command = CreateSpCommand(connection, code)) | |
using (var reader = command.ExecuteReader(CommandBehavior.SequentialAccess)) | |
{ | |
return reader.ToEnumerable() | |
.Select(RecordToEntry) | |
.Where(entry => entry.VariationRate != null) | |
.ToList(); | |
} | |
} | |
private static Currency RecordToEntry(IDataRecord record) | |
{ | |
return new Currency( | |
record.GetOrDefault("Code", string.Empty).Trim(), | |
record.GetOrDefault("Name", string.Empty).Trim(), | |
record.GetOrDefault("DecimalPlaces", 0), | |
record.GetOrDefault<int?>("VariationRate")); | |
} | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment