Skip to content

Instantly share code, notes, and snippets.

@Scooletz
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Scooletz/402cee0cb04e04378788 to your computer and use it in GitHub Desktop.
Save Scooletz/402cee0cb04e04378788 to your computer and use it in GitHub Desktop.
ArraySegment possible to use with SqlCommand
[Test]
public void TestChunks()
{
const string connectionString = @"YOUR_DB";
const string insertEvent = "INSERT INTO Events (id, payload) VALUES(@id, @payload)";
const int testSize = 10;
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var tx = con.BeginTransaction(IsolationLevel.ReadUncommitted))
{
var sql = new SqlCommand(insertEvent, con, tx);
var id = sql.Parameters.Add("@id", SqlDbType.BigInt);
var payload = sql.Parameters.Add("@payload", SqlDbType.Binary);
var buffer = new byte[1024];
using (var ms = new MemoryStream(buffer))
{
var writer = new BinaryWriter(ms, Encoding.UTF8, true);
var values = Enumerable.Range(0, testSize).Select(i=>(long)i).ToArray();
foreach (var i in values)
{
payload.Value = buffer;
payload.Offset = (int)ms.Position;
payload.Size = Marshal.SizeOf(typeof(long));
writer.Write(i);
id.Value = i;
sql.ExecuteNonQuery();
}
var select = new SqlCommand("SELECT payload FROM Events WHERE id IN ({ids})", con, tx);
select.AddParameters(values, "ids");
var list = new List<long>();
using (var reader = @select.ExecuteReader())
{
while (reader.Read())
{
list.Add(BitConverter.ToInt64((byte[])reader[0], 0));
}
}
CollectionAssert.AreEqual(values, list);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment