ADO.NET Provider for Microsoft Excel

Build 23.0.8839

Code-First Approach

An alternative to introspecting the model from the provider is to handwrite your model classes. This is the code-first approach to Entity Framework, which gives you greater control over the exact data model you use in your application.

Create the Context Class

This is the base object that extends DbContext and exposes the DbSet properties that represent the tables in the data source. Override some of the default functionality of the DbContext class by overriding the OnConfiguring method.

using Microsoft.EntityFrameworkCore;

public class ExcelContext : DbContext
{
	public DbSet<Sheet> Sheet { get; set; }

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		if (!optionsBuilder.IsConfigured)
		{
			optionsBuilder.UseExcel("URI=C:\MyExcelWorkbooks\SampleWorkbook.xlsx;");
		}
	}
}

Create the Table Models

Define a class for each table that was defined in the DbSet properties of the context class. The table classes should have a list of properties that correspond to each field of that table. A corresponding map class must be defined to configure attributes for each property in the table class.

public class Sheet
{
	public string RowId { get; set; }
	public string LastName { get; set; }
}

Retrieving Records

You can retrieve records from a table as follows:

class Program
	{
		static void Main(string[] args)
		{
			SalesforceContext context = new SalesforceContext();var Query = from Lead in context.Leadselect Lead;
			foreach (var result in Query)
			{
				Console.WriteLine("{0}", result.Id);
				Console.WriteLine("{0}", result.LastName);
			}
			try
			{
				context.SaveChanges();
			}
			catch (Exception e)
			{
				Console.WriteLine(e);
			}
			Console.ReadLine();
		}
	}

Inserting Records

You can insert records into existing tables as follows:

class Program
	{
		static void Main(string[] args)
		{
			SalesforceContext context = new SalesforceContext();
			Lead newRecord = new Lead()
			{
				Company = "Company", LastName = "Iris1"
			};
			context.Lead.Add(newRecord);
			try
			{
				context.SaveChanges();
				Console.WriteLine(newRecord.Id);
			}
			catch (Exception e)
			{
				Console.WriteLine(e);
			}
			Console.ReadLine();
		}
	}

Copyright (c) 2024 CData Software, Inc. - All rights reserved.
Build 23.0.8839