The Sharp Factory
Esc
↑ ↓ to moveEnter to open
Getting Started / Project Setup

Project Setup

Add the package, the connection string and the repository container to the project that uses the generated code.

10 steps · app screens and real code
On this page

Required NuGet Package#

The generated code talks to SQL Server through Microsoft.Data.SqlClient. Sync adds this NuGet package when it creates the generated Repository project (the project that contains the Database class and the repositories), so usually there is nothing to do.

Add it yourself only when you use sharpfactory generate (which writes no project files), or when the Repository project existed before the first Sync; for example from its folder:

dotnet add package Microsoft.Data.SqlClient

When the database has geography or geometry columns, also add the Microsoft.SqlServer.Types package to the generated Entity project; without it the solution does not build ("The type or namespace name 'Types' does not exist in the namespace 'Microsoft.SqlServer'"):

dotnet add package Microsoft.SqlServer.Types

Connection String#

Before you can interact with the database from your application using The Sharp Factory Framework you will need to register the connection string.

Because multiple models are supported you will need to register one connection string per model in your project.

Since version 4.0, Microsoft.Data.SqlClient encrypts connections by default, which requires a certificate on the server. If your SQL Server has no certificate (common on development and test servers), add Encrypt=False to your application's connection string, for example:

Data Source=localhost;Initial Catalog=AppDb;Integrated Security=True;Encrypt=False

Registering The Connection String#

We recommend registering the connection string(s) early in the execution pipeline.

For example in your Program.cs class; more specifically in your Main method. Or in the configured entry point for your application.

The Database.RegisterModelConnectionString takes 2 parameters:

  1. int modelId: The code generator assigns a unique model id to each model added to the model container. This can easily be accessed from the RepoLookup.ModelId static class.

  2. string connectionString: This is the connection string that your application will use during runtime to access the database.

The Repository Container#

The RepositoryContainer class is the starting point for all data access and manipulation. This class does not keep any state. This means it can be used as a singleton and we recommend you do so. However you are not constraint to do so if you wish otherwise.

Your First Program#

After Sync, the generated projects are in your solution. From the solution's folder, add a console app that references the generated Repository project (here the root namespace is MyApp and the projects are in the Dependencies folder):

Command line
dotnet new console -n ShopDemodotnet sln add ShopDemodotnet add ShopDemo reference Dependencies/MyApp.Repository/MyApp.Repository.csproj

Then replace its Program.cs with the code below. It reads the sample database. For your own database, use your connection string and your model's names: MyApp is the root namespace, AppDb the model, Sales the schema and Customer the table.

C#
// Program.cs of a console app that references the generated Repository project// MyApp is the root namespace chosen when the model was created: use yoursusing MyApp.Entity.AppDb.Sales;using MyApp.Query;using MyApp.Repository.Common;using MyApp.Repository.Container;// register the connection string of each model once, when the application startsDatabase.RegisterModelConnectionString(RepoLookup.ModelId.AppDb,    "Server=localhost;Database=SharpFactoryShop;Integrated Security=true;Encrypt=False");// the starting point for all data access: it keeps no state,// so one instance can serve the whole applicationvar repo = new RepositoryContainer();// every customervar customers = repo.AppDb.Sales.Customer.ToList();Console.WriteLine($"{customers.Count} customers");// one customer by primary keyvar customer = repo.AppDb.Sales.Customer.ByPK(3);Console.WriteLine($"Customer 3 is {customer.Name} {customer.LastName}");// customers with a balance over 300, the largest firstvar query = new Query<CustomerProperty>()    .BeginPredicate()        .Where(CustomerProperty.Balance).GreaterThan(300m)    .EndPredicate()    .BeginSorting()        .OrderByDescending(CustomerProperty.Balance)    .EndSorting();foreach (var c in repo.AppDb.Sales.Customer.ToList(query)){    Console.WriteLine($"{c.Name} {c.LastName}: {c.Balance}");}

Run it with dotnet run --project ShopDemo. It prints:

Output
12 customersCustomer 3 is Chloe NguyenChloe Nguyen: 1240.50Farid Haddad: 980.00Isla Bennett: 410.75Keiko Sato: 330.00

No SQL Server on localhost? The sample database page has the connection strings for LocalDB and Docker.

Namespaces#

The samples in this documentation leave out their using lines. These are the ones they need, with MyApp as the root namespace, AppDb as the model and Sales as the schema:

NamespaceFor
MyApp.Repository.CommonDatabase and RepoLookup: the connection strings and query logging
MyApp.Repository.ContainerRepositoryContainer, the way to every repository
MyApp.QueryQuery<T> and NavProps<T>
MyApp.Entity.AppDb.SalesThe schema's entities (Customer), their property containers (CustomerProperty, CustomerNavProperty) and the requests of its procedures and functions (GetCustomersByCity_Request)
MyApp.Repository.Container.InterfacesIRepositoryContainer, for dependency injection

Each schema of each model has its own MyApp.Entity.{Model}.{Schema} namespace.

Something wrong or unclear on this page? Tell us on GitHub