Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
Vigtigt!
Denne funktion er i prøveversion.
ADO.NET er en bredt anvendt dataadgangsteknologi i .NET-økosystemet, som gør det muligt for applikationer at forbinde til og arbejde med data fra databaser og big data-platforme.
Microsoft ADO.NET Driver for Fabric Data Engineering lader dig forbinde, forespørge og administrere Spark-arbejdsbelastninger i Microsoft Fabric med pålideligheden og enkelheden fra standard ADO.NET-mønstre. Drevet på Microsoft Fabrics Livy API'er leverer sikker og fleksibel Spark SQL-forbindelse til dine .NET-applikationer ved hjælp af velkendte DbConnection, DbCommand, og DbDataReader abstraktioner.
Vigtige funktioner
-
ADO.NET Compliant: Fuld implementering af ADO.NET abstraktioner (
DbConnection,DbCommand,DbDataReader,DbParameter, , )DbProviderFactory - Microsoft Entra ID-autentificering: Flere autentificeringsflows, herunder Azure CLI, interaktiv browser, klientoplysninger, certifikatbaseret og adgangstoktoeifikation
- Spark SQL Native Query Support: Direkte udførelse af Spark SQL-udsagn med parameteriserede forespørgsler
- Omfattende understøttelse af datatyper: Understøttelse af alle Spark SQL-datatyper inklusive komplekse typer (ARRAY, MAP, STRUCT)
- Connection Pooling: Indbygget administration af forbindelsespoolen for forbedret ydeevne
- Genbrug af sessioner: Effektiv Spark-sessionstyring for at reducere opstartsforsinkelse
- Async Prefetch: Baggrundsindlæsning af data for forbedret ydeevne med store resultatsæt
- Auto-genforbindelse: Automatisk sessionsgendannelse efter forbindelsesfejl
Bemærkning
I open source Apache Spark bruges database og skema synonymt. For eksempel returnerer det samme resultat, hvis man kører SHOW SCHEMAS eller SHOW DATABASES i en Fabric Notebook — en liste over alle skemaer i Lakehouse.
Forudsætninger
Før du bruger Microsoft ADO.NET Driver for Microsoft Fabric Data Engineering, skal du sikre dig, at du har:
- .NET Runtime: .NET 8.0 eller senere
- Microsoft Fabric Access: Adgang til et Microsoft Fabric-arbejdsområde med Data Engineering-funktioner
- Azure Entra ID Credentials: Passende legitimationsoplysninger til autentificering
- Workspace og Lakehouse ID'er: GUID-identifikatorer for dit Fabric workspace og lakehouse
- Azure CLI (valgfrit): Required for Azure CLI authentication method
Download, inkludér, referer og verificér
Download NuGet-pakken
Microsoft ADO.NET Driver for Microsoft Fabric Data Engineering version 1.0.0 er i offentlig forhåndsvisning, som du kan downloade fra disse downloadcenter-links.
- Download Microsoft ADO.NET Driver til Microsoft Fabric Data Engineering (zip)
- Download Microsoft ADO.NET Driver til Microsoft Fabric Data Engineering (tar)
Reference NuGet-pakke i dit projekt
Inkluder den downloadede NuGet-pakke i dit projekt og tilføj en reference til pakken til din projektfil:
<ItemGroup>
<PackageReference Include="Microsoft.Spark.Livy.AdoNet" Version="1.0.0" />
</ItemGroup>
Kontrollér installationen
Efter inkludering og reference, skal du sikre dig, at pakken er tilgængelig i dit projekt:
using Microsoft.Spark.Livy.AdoNet;
// Verify the provider is registered
var factory = LivyProviderFactory.Instance;
Console.WriteLine($"Provider: {factory.GetType().Name}");
Eksempel på hurtigstart
using Microsoft.Spark.Livy.AdoNet;
// Connection string with required parameters
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=AzureCli;";
// Create and open connection
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync();
Console.WriteLine("Connected successfully!");
// Execute a query
using var command = connection.CreateCommand();
command.CommandText = "SELECT 'Hello from Fabric!' as message";
using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
Console.WriteLine(reader.GetString(0));
}
Forbindelsesstrengsformat
Grundformat
Microsoft ADO.NET Driver bruger standard ADO.NET forbindelsesstrengsformat:
Parameter1=Value1;Parameter2=Value2;...
Påkrævede parametre
| Parameter | Beskrivelse | Eksempel |
|---|---|---|
Server |
Microsoft Fabric API-endpoint | https://api.fabric.microsoft.com/v1 |
SparkServerType |
Servertypeidentifikator | Fabric |
FabricWorkspaceID |
Microsoft Fabric arbejdsområdeidentifikator (GUID) | <workspace-id> |
FabricLakehouseID |
Microsoft Fabric lakehouse-identifikator (GUID) | <lakehouse-id> |
AuthFlow |
Godkendelsesmetode |
AzureCli, BrowserBased, ClientSecretCredential, ClientCertificateCredentialAuthAccessTokenFileToken |
Valgfrie parametre
Forbindelsesindstillinger
| Parameter | Type | Standard | Beskrivelse |
|---|---|---|---|
LivySessionTimeoutSeconds |
Integer | 60 |
Tid på sekunder til at vente på oprettelse af sessioner |
LivyStatementTimeoutSeconds |
Integer | 600 |
Tid i sekunder til at vente på sætningsudførelse |
SessionName |
String | (auto) | Brugerdefineret navn for Spark-sessionen |
AutoReconnect |
Boolean | false |
Aktivér automatisk sessionsgendannelse |
Indstillinger for forbindelsespoolen
| Parameter | Type | Standard | Beskrivelse |
|---|---|---|---|
ConnectionPoolEnabled |
Boolean | true |
Aktiver forbindelsespooling |
MinPoolSize |
Integer | 1 |
Minimum forbindelser i poolen |
MaxPoolSize |
Integer | 20 |
Maksimale forbindelser i poolen |
ConnectionMaxIdleTimeMs |
Integer | 1800000 |
Maksimal tomgangstid før forbindelsen genanvendes (30 min) |
MaxLifetimeMs |
Integer | 3600000 |
Maksimal levetid for en poolet forbindelse (60 min) |
ValidateConnections |
Boolean | true |
Valider forbindelser før brug |
ValidationTimeoutMs |
Integer | 5000 |
Timeout for forbindelsesvalidering |
Logningsindstillinger
| Parameter | Type | Standard | Beskrivelse |
|---|---|---|---|
LogLevel |
String | Information |
Log-niveau: Trace, Debug, Information, , WarningError |
LogFilePath |
String | (ingen) | Sti for filbaseret logning |
Bemærkning
Cross-driver-aliaser: Driveren accepterer JDBC- og ODBC-ejendomsnavne ud over native ADO.NET-navne (f.eks. WorkspaceId kort til FabricWorkspaceID, LakehouseId kort til FabricLakehouseID). Alle ejendomsnavne er små og små bogstaver.
Eksempel på forbindelsesstrenge
Basic connection (Azure CLI authentication)
Server=https://api.fabric.microsoft.com/v1;SparkServerType=Fabric;FabricWorkspaceID=<workspace-id>;FabricLakehouseID=<lakehouse-id>;AuthFlow=AzureCli
Med forbindelsespooling-muligheder
Server=https://api.fabric.microsoft.com/v1;SparkServerType=Fabric;FabricWorkspaceID=<workspace-id>;FabricLakehouseID=<lakehouse-id>;AuthFlow=AzureCli;ConnectionPoolEnabled=true;MinPoolSize=2;MaxPoolSize=10
Med automatisk genforbindelse og logning
Server=https://api.fabric.microsoft.com/v1;SparkServerType=Fabric;FabricWorkspaceID=<workspace-id>;FabricLakehouseID=<lakehouse-id>;AuthFlow=AzureCli;AutoReconnect=true;LogLevel=Debug
Godkendelse
Microsoft ADO.NET Driver understøtter flere autentificeringsmetoder via Microsoft Entra ID (tidligere Azure Active Directory). Autentificering konfigureres ved hjælp af parameteren AuthFlow i forbindelsesstrengen.
Godkendelsesmetoder
| AuthFlow-værdi | Beskrivelse | Bedst til |
|---|---|---|
AzureCli |
Bruger Azure CLI cachede credentials | Udvikling og test |
BrowserBased |
Interaktiv browserbaseret autentificering | Brugerrettede applikationer |
ClientSecretCredential |
Serviceprincipal med klienthemmelighed | Automatiserede tjenester, baggrundsopgaver |
ClientCertificateCredential |
Servicechef med certifikat | Virksomhedsprogrammer |
AuthAccessToken |
Foruderhvervet bæreradgangstoken | Brugerdefinerede autentificeringsscenarier |
Azure CLI authentication
Bedst til: Udvikling og testning
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=AzureCli;";
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync();
Forudsætninger:
- Azure CLI installeret:
az --version - Indlogget:
az login
Interaktiv browserautentificering
Bedst til: Brugerrettede applikationer
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=BrowserBased;" +
"AuthTenantID=<tenant-id>;";
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync(); // Opens browser for authentication
Adfærd:
- Åbner et browservindue til brugerautentificering
- Oplysninger caches til efterfølgende forbindelser
Klientlegitimation (service principal) autentificering
Bedst til: Automatiserede tjenester og baggrundsjobs
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=ClientSecretCredential;" +
"AuthTenantID=<tenant-id>;" +
"AuthClientID=<client-id>;" +
"AuthClientSecret=<client-secret>;";
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync();
Påkrævede parametre:
-
AuthTenantID: Azure tenant ID -
AuthClientID: Application (klient) ID fra Microsoft Entra ID -
AuthClientSecret: Klienthemmelighed fra Microsoft Entra ID
Certifikatbaseret godkendelse
Bedst til: Virksomhedsapplikationer, der kræver certifikatbaseret autentificering
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=ClientCertificateCredential;" +
"AuthTenantID=<tenant-id>;" +
"AuthClientID=<client-id>;" +
"AuthCertificatePath=C:\\certs\\mycert.pfx;" +
"AuthCertificatePassword=<password>;";
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync();
Påkrævede parametre:
-
AuthTenantID: Azure tenant ID -
AuthClientID: Applikations-ID (klient) -
AuthCertificatePath: Sti til PFX/PKCS12 certifikatfil -
AuthCertificatePassword: Certifikatadgangskode
Adgangstoksgodkendelse
Bedst til: Brugerdefinerede autentificeringsscenarier
// Acquire token through your custom mechanism
string accessToken = await AcquireTokenFromCustomSourceAsync();
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=AuthAccessToken;" +
$"AuthAccessToken={accessToken};";
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync();
Bemærkning
Vi anbefaler kraftigt at undgå hårdkodning af legitimationsoplysninger som adgangskoder, nøgler, hemmeligheder, tokens eller certifikater i din kode. Brug i stedet Azure Key Vault til sikkert at gemme disse værdier og hente dem under kørsel.
Eksempler på anvendelse
Grundlæggende forbindelse og forespørgsel
using Microsoft.Spark.Livy.AdoNet;
string connectionString =
"Server=https://api.fabric.microsoft.com/v1;" +
"SparkServerType=Fabric;" +
"FabricWorkspaceID=<workspace-id>;" +
"FabricLakehouseID=<lakehouse-id>;" +
"AuthFlow=AzureCli;";
using var connection = new LivyConnection(connectionString);
await connection.OpenAsync();
Console.WriteLine($"Connected! Server version: {connection.ServerVersion}");
// Execute a query
using var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM employees LIMIT 10";
using var reader = await command.ExecuteReaderAsync();
// Print column names
for (int i = 0; i < reader.FieldCount; i++)
{
Console.Write($"{reader.GetName(i)}\t");
}
Console.WriteLine();
// Print rows
while (await reader.ReadAsync())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.Write($"{reader.GetValue(i)}\t");
}
Console.WriteLine();
}
Parameteriserede forespørgsler
using var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM orders WHERE order_date >= @startDate AND status = @status";
// Add parameters
command.Parameters.AddWithValue("@startDate", new DateTime(2024, 1, 1));
command.Parameters.AddWithValue("@status", "completed");
using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine($"Order: {reader["order_id"]}, Total: {reader["total"]:C}");
}
ExecuteScalar for enkeltværdier
using var command = connection.CreateCommand();
command.CommandText = "SELECT COUNT(*) FROM customers";
var count = await command.ExecuteScalarAsync();
Console.WriteLine($"Total customers: {count}");
ExecuteNonQuery for DML-operationer
// INSERT
using var insertCommand = connection.CreateCommand();
insertCommand.CommandText = @"
INSERT INTO employees (id, name, department, salary)
VALUES (100, 'John Doe', 'Engineering', 85000)";
int rowsAffected = await insertCommand.ExecuteNonQueryAsync();
Console.WriteLine($"Inserted {rowsAffected} row(s)");
// UPDATE
using var updateCommand = connection.CreateCommand();
updateCommand.CommandText = "UPDATE employees SET salary = 90000 WHERE id = 100";
rowsAffected = await updateCommand.ExecuteNonQueryAsync();
Console.WriteLine($"Updated {rowsAffected} row(s)");
// DELETE
using var deleteCommand = connection.CreateCommand();
deleteCommand.CommandText = "DELETE FROM employees WHERE id = 100";
rowsAffected = await deleteCommand.ExecuteNonQueryAsync();
Console.WriteLine($"Deleted {rowsAffected} row(s)");
Arbejde med store resultatmængder
using var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM large_table";
using var reader = await command.ExecuteReaderAsync();
int rowCount = 0;
while (await reader.ReadAsync())
{
// Process each row
ProcessRow(reader);
rowCount++;
if (rowCount % 10000 == 0)
{
Console.WriteLine($"Processed {rowCount} rows...");
}
}
Console.WriteLine($"Total rows processed: {rowCount}");
Skemaopdagelse
// List all tables
using var showTablesCommand = connection.CreateCommand();
showTablesCommand.CommandText = "SHOW TABLES";
using var tablesReader = await showTablesCommand.ExecuteReaderAsync();
Console.WriteLine("Available tables:");
while (await tablesReader.ReadAsync())
{
Console.WriteLine($" {tablesReader.GetString(0)}");
}
// Describe table structure
using var describeCommand = connection.CreateCommand();
describeCommand.CommandText = "DESCRIBE employees";
using var schemaReader = await describeCommand.ExecuteReaderAsync();
Console.WriteLine("\nTable structure for 'employees':");
while (await schemaReader.ReadAsync())
{
Console.WriteLine($" {schemaReader["col_name"]}: {schemaReader["data_type"]}");
}
Brug af LivyConnectionStringBuilder
using Microsoft.Spark.Livy.AdoNet;
var builder = new LivyConnectionStringBuilder
{
Server = "https://api.fabric.microsoft.com/v1",
SparkServerType = "Fabric",
FabricWorkspaceID = "<workspace-id>",
FabricLakehouseID = "<lakehouse-id>",
AuthFlow = "AzureCli",
ConnectionPoolingEnabled = true,
MinPoolSize = 2,
MaxPoolSize = 10,
ConnectionTimeout = 60
};
using var connection = new LivyConnection(builder.ConnectionString);
await connection.OpenAsync();
Brug af DbProviderFactory
using System.Data.Common;
using Microsoft.Spark.Livy.AdoNet;
// Register the provider factory (typically done at application startup)
DbProviderFactories.RegisterFactory("Microsoft.Spark.Livy.AdoNet", LivyProviderFactory.Instance);
// Create connection using factory
var factory = DbProviderFactories.GetFactory("Microsoft.Spark.Livy.AdoNet");
using var connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
await connection.OpenAsync();
using var command = factory.CreateCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM employees LIMIT 5";
using var reader = await command.ExecuteReaderAsync();
// Process results...
Datatypetilknytning
Driveren mapper Spark SQL-datatyper til .NET-typer:
| Spark SQL Type | .NET-type | DbType |
|---|---|---|
| BOOLESK | bool |
Boolean |
| TINYINT | sbyte |
SByte |
| SMALLINT | short |
Indt16 |
| INT | int |
Int32 |
| BIGINT | long |
Int64 |
| FLYDE | float |
Enlig |
| DOBBELT | double |
Dobbelt |
| DECIMAL(p,s) | decimal |
Decimal |
| STRENG | string |
String |
| VARCHAR(n) | string |
String |
| CHAR(n) | string |
String |
| BINÆR | byte[] |
Binary |
| DATO | DateTime |
Dato |
| TIDSSTEMPEL | DateTime |
Dato og klokkeslæt |
| ARRAY<T> |
T[] eller string (JSON) |
Objekt |
| MAP<K,V> |
Dictionary<K,V> eller string (JSON) |
Objekt |
| STRUCT |
object eller string (JSON) |
Objekt |
Arbejde med komplekse typer
Komplekse typer (ARRAY, MAP, STRUCT) returneres som JSON-strenge som standard:
using System.Text.Json;
using System.Collections.Generic;
using var command = connection.CreateCommand();
command.CommandText = "SELECT array_column, map_column, struct_column FROM complex_table LIMIT 1";
using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
// Complex types returned as JSON strings
string arrayJson = reader.GetString(0); // e.g., "[1, 2, 3]"
string mapJson = reader.GetString(1); // e.g., "{\"key\": \"value\"}"
string structJson = reader.GetString(2); // e.g., "{\"field1\": 1, \"field2\": \"text\"}"
// Parse with System.Text.Json
var array = JsonSerializer.Deserialize<int[]>(arrayJson);
var map = JsonSerializer.Deserialize<Dictionary<string, string>>(mapJson);
}
Fejlfinding
Dette afsnit giver vejledning til at løse almindelige problemer, du kan støde på, når du bruger Microsoft ADO.NET Driver til Microsoft Fabric Data Engineering.
Almindelige problemer
Følgende afsnit beskriver almindelige problemer og deres løsninger:
Forbindelsesfejl
Problem: Kan ikke oprette forbindelse til Microsoft Fabric
Løsninger:
- Verificér
FabricWorkspaceIDogFabricLakehouseIDer korrekte GUID'er - Check Azure CLI authentication:
az account show - Sørg for, at du har passende Fabric-arbejdsområdetilladelser
- Verificér netværksforbindelsen til
api.fabric.microsoft.com
Godkendelsesfejl
Problem: Autentificering fejler med Azure CLI
Løsninger:
- Kør
az loginfor at opdatere legitimationsoplysninger - Verificér korrekt lejer:
az account set --subscription <subscription-id> - Tjek tokens gyldighed:
az account get-access-token --resource https://api.fabric.microsoft.com
Timeout for forespørgsler
Problem: Forespørgsler går ud på tid på store tabeller
Løsninger:
- Øg udtogstimeout:
LivyStatementTimeoutSeconds=300 - Brug
LIMITklausulen til at begrænse resultatstørrelsen under udviklingen - Sørg for, at Spark-klyngen har tilstrækkelige ressourcer
Timeout for sessionsoprettelse
Problem: Forbindelsen går ud under sessionoprettelsen
Løsninger:
- Øg timeouten i sessionen:
LivySessionTimeoutSeconds=120 - Tjek tilgængelighed af Fabric-kapacitet
- Bekræfte, at arbejdsområdet ikke har nået sessionsgrænser
Aktiver logning
Når du fejlsøger problemer, kan det hjælpe dig at aktivere detaljeret logning med at identificere den grundlæggende årsag til problemerne. Du kan aktivere logging via forbindelsesstrengen eller programmatisk.
For at muliggøre detaljeret logning via forbindelsesstreng:
LogLevel=Debug
Eller konfigurere programmatisk:
using Microsoft.Extensions.Logging;
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
builder.SetMinimumLevel(LogLevel.Debug);
});
// Logging is automatically integrated with the connection
Log-niveauer:
-
Trace: Mest omstændelig, inkluderer alle API-kald -
Debug: Detaljeret fejlfinding information -
Information: Generel information (standard) -
Warning: Kun advarsler -
Error: Kun fejl