Can an SqlDataReader be passed to a session or sent to a client?
For instance, if I retrieved some rows from a database, and want to send this data to another client machine. Can I simply do this by serializing it using json on the server and then deserializing back on the client?
不,只有数据(没有方法或功能)可以被序列化,所以数据阅读器将是无用的,因为你无法调用方法来推进阅读器等。模式是将所有记录读入一个对象列表中阅读器,关闭它,然后将这些对象序列化回客户端。
No, any resource-related object cannot be "passed" to a client.
This wouldn't really make sense. You should "materialize" the data reader and pass the results.
Ie you can create an SqlDataAdapter from your reader, fill a DataTable and pass the DataTable.
No, you have to map the reader to a POCO and that will be serialized. Even if you can technically serialize the SqlDatReader object, it's a VERY BAD Idea. Don't do it. It's trivial to use a micro-orm to map a query to a DTO. Don't complicate your work.
Old Question, but technology provide new solutions.
You can use Protocol Buffers DataReader Extensions for .NET to Serialize SqlDataReader and can be passed to a session or sent to a client
Example:
string connstring1 = "Data Source=server1;Initial Catalog=northwind;user=xxx;password=xxx";
//Serializing an IDataReader into a ProtoBuf:
Stream buffer = new MemoryStream();
using (var c1 = new SqlConnection(connstring1))
{
c1.Open();
// Serialize SQL results to a buffer
using (var command = new SqlCommand("SELECT * FROM products", c1))
using (var reader = command.ExecuteReader())
DataSerializer.Serialize(buffer, reader);
// Read them back
buffer.Seek(0, SeekOrigin.Begin);
using (var reader = DataSerializer.Deserialize(buffer))
{
while (reader.Read())
{
Console.WriteLine(reader["ProductName"]);
}
}
}
}
you should install nuget package:
Install-Package protobuf-net-data
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.