Last active
August 29, 2015 14:10
-
-
Save Scooletz/402cee0cb04e04378788 to your computer and use it in GitHub Desktop.
ArraySegment possible to use with SqlCommand
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
[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