SqlSugar/Src/Asp.NetCore2/MongoDb.Ado.data/MongoDbDataReader.cs

88 lines
2.6 KiB
C#
Raw Normal View History

2025-04-26 19:46:11 +08:00
using System;
using System.Collections.Generic;
using System.Data.Common;
using MongoDB.Driver;
using MongoDB.Bson;
using System.Data;
using System.Collections;
2025-05-02 14:30:13 +08:00
using System.Linq;
2025-05-05 14:26:49 +08:00
using MongoDB.Bson.Serialization;
2025-04-26 19:46:11 +08:00
namespace MongoDb.Ado.data
{
2025-07-03 13:13:49 +08:00
public static class MongoDbDataReaderHelper
2025-05-02 11:39:41 +08:00
{
2025-07-03 13:13:49 +08:00
public static DbDataReader ToDataReader(IEnumerable<BsonDocument> documents)
2025-05-02 11:39:41 +08:00
{
2025-07-03 13:13:49 +08:00
var table = new DataTable();
var allFields = new HashSet<string>();
2025-05-02 11:39:41 +08:00
2025-07-03 13:13:49 +08:00
// 收集所有字段名
foreach (var doc in documents)
2025-05-02 11:39:41 +08:00
{
2025-07-03 13:13:49 +08:00
foreach (var elem in doc.Elements)
{
allFields.Add(elem.Name);
}
2025-05-02 11:39:41 +08:00
}
2025-07-03 13:13:49 +08:00
// 建立DataTable列类型object支持多类型和DBNull
foreach (var field in allFields)
2025-05-05 14:26:49 +08:00
{
2025-07-03 13:13:49 +08:00
table.Columns.Add(field, typeof(object));
2025-05-05 14:26:49 +08:00
}
2025-05-02 11:39:41 +08:00
2025-07-03 13:13:49 +08:00
// 填充DataTable行
foreach (var doc in documents)
2025-05-02 11:39:41 +08:00
{
2025-07-03 13:13:49 +08:00
var row = table.NewRow();
foreach (var field in allFields)
{
if (doc.Contains(field))
{
var val = doc[field];
row[field] = val.IsBsonNull ? DBNull.Value : ConvertBsonValue(val);
}
else
{
row[field] = DBNull.Value;
}
}
table.Rows.Add(row);
2025-05-02 11:39:41 +08:00
}
2025-07-03 13:13:49 +08:00
// 返回IDataReader
return table.CreateDataReader();
2025-05-02 11:39:41 +08:00
}
2025-07-04 09:27:33 +08:00
public static object ConvertBsonValue(BsonValue val)
2025-05-02 11:39:41 +08:00
{
2025-07-03 13:13:49 +08:00
if (val == null || val.IsBsonNull)
return DBNull.Value;
2025-05-02 11:39:41 +08:00
2025-07-03 13:13:49 +08:00
switch (val.BsonType)
2025-05-02 11:39:41 +08:00
{
2025-07-03 13:13:49 +08:00
case BsonType.Int32:
return val.AsInt32;
case BsonType.Int64:
return val.AsInt64;
case BsonType.Double:
return val.AsDouble;
case BsonType.String:
return val.AsString;
case BsonType.Boolean:
return val.AsBoolean;
case BsonType.DateTime:
return val.ToUniversalTime();
case BsonType.Decimal128:
return val.AsDecimal;
case BsonType.ObjectId:
return val.AsObjectId.ToString();
// 其他类型可以扩展
default:
return val;
2025-05-02 11:39:41 +08:00
}
}
}
2025-04-26 19:46:11 +08:00
}