title
stringlengths
3
46
content
stringlengths
0
1.6k
12:302
The Cosmos DB provider for Entity Framework Core is contained in the Microsoft.EntityFrameworkCore.Cosmos NuGet package. Once you’ve added this to your project, you can proceed in a similar way to when you used the SQL Server provider in Chapter 13, Interacting with Data in C# – Entity Framework Core, but with a few differences. Let us take a look:
12:303
12:304
There are no migrations since Cosmos DB databases have no structure to update. Instead, they have a method that ensures that the database, along with all the necessary collections, is created:
12:305
context.Database.EnsureCreated();
12:306
12:307
12:308
By default, the DbSet<T> properties from DBContext are mapped to a unique container since this is the cheapest option. You can override this default by explicitly specifying which container you want to map some entities to by using the following configuration instruction:
12:309
builder.Entity<MyEntity>()
12:310
.ToContainer(`collection-name`);
12:311
12:312
12:313
The only useful annotation on entity classes is the Key attribute, which becomes obligatory when the primary keys are not called Id.
12:314
Primary keys must be strings and cannot be auto-incremented to avoid synchronization issues in a distributed environment. The uniqueness of primary keys can be ensured by generating GUIDs and transforming them into strings.
12:315
When defining relationships between entities, you can specify that an entity or a collection of entities is owned by another entity, in which case it is stored together with the parent entity.
12:316
12:317
We will look at the usage of Cosmos DB’s Entity Framework provider in the How to choose your data storage in the cloud section of Chapter 21, Case Study.
12:318
Summary
12:319
In this chapter, we looked at the main storage options available in Azure and learned when to use them. Then, we compared relational and NoSQL databases. We pointed out that relational databases offer automatic consistency checking and transaction isolation, but NoSQL databases are cheaper and offer better performance, especially when distributed writes form a high percentage of the average workload.
12:320
Then, we described Azure’s main NoSQL option, Cosmos DB, and explained how to configure it and how to connect with a client.
12:321
Finally, we learned how to interact with Cosmos DB with Entity Framework Core. Here, we learned how to decide whether to use relational or NoSQL databases for all families of data involved in an application. So, you can choose the kind of data storage that ensures the best compromise between data coherence, speed, and parallel access to data in each of your applications.
12:322
In the next chapter, we will learn all about how to interact with data in C#–Entity Framework Core.
12:323
Questions
12:324
12:325
Is Redis a valid alternative to relational databases?
12:326
Are NoSQL databases a valid alternative to relational databases?
12:327
What operation is more difficult to scale out in relational databases?
12:328
What is the main weakness of NoSQL databases? What is their main advantage?
12:329
Can you list all Cosmos DB consistency levels?
12:330
Can we use auto-increment integer keys with Cosmos DB?
12:331
Which Entity Framework configuration method is used to store an entity inside its related father document?
12:332
Can nested collections be searched efficiently with Cosmos DB?
12:333
12:334
Further reading
12:335
12:336
The following is a reference to the Gremlin language, which is supported by Cosmos DB: http://tinkerpop.apache.org/docs/current/reference/#graph-traversal-steps.
12:337
The following is a general description of the Cosmos DB graph data model: https://docs.microsoft.com/en-us/azure/cosmos-db/graph-introduction.
12:338
Details on how to use Cosmos DB’s official .NET client can be found at https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-dotnetcore-get-started. A good introduction to the MvcControlsToolkit.Business.DocumentDB NuGet package that we mentioned in this chapter is the Fast Azure Cosmos DB Development with the DocumentDB Package article contained in Issue 34 of DNCMagazine. This can be downloaded from https://www.dotnetcurry.com/microsoft-azure/aspnet-core-cosmos-db-documentdb.
12:339
12:340
Learn more on Discord
12:341
To join the Discord community for this book – where you can share feedback, ask questions to the authors, and learn about new releases – follow the QR code below:
12:342
https://packt.link/SoftwareArchitectureCSharp12Dotnet8
12:343
12:344
12:345
13:1
Interacting with Data in C# – Entity Framework Core
13:2
As we mentioned in Chapter 7, Understanding the Different Domains in Software Solutions, software systems are organized into layers that communicate with each other through interfaces and classes that don’t depend on how the peculiarities of each layer are implemented. When the software is a business/enterprise system, it usually contains at least three layers: the data layer, the business layer, and the presentation layer, if the software is based on a classical layer architecture (see the Classic layers architecture section of Chapter 7.
13:3
If, instead, the application is based on an onion architecture, an outermost layer contains presentation logic, drivers, and testing logic, then there is an application layer, and finally, a domain layer (see the Onion architecture section of Chapter 7). While, in the onion architecture, layers are defined in a slightly different way, the functionalities of the three layers of the onion architecture are basically the same as the ones of the three layers of the classical layer architecture.
13:4
However, notwithstanding the differences among all possible architectural choices, experience has proved that the main functionalities needed to handle data efficaciously are quite standard.
13:5
More specifically, in all architectures described in Chapter 7, data-processing layers have the main purpose of mapping data from a data storage subsystem into objects and vice versa.
13:6
In the case of the classical data layer, these objects are plain objects with no methods, while in the case of the domain layer, they are rich objects whose methods implement the application’s domain logic. Data layers, instead, implement the application’s domain logic within repository classes that are associated with their plain objects (see the The Repository and Unit of Work patterns section of Chapter 7).
13:7
This led to the conception of general-purpose frameworks for implementing data layers in a substantially declarative way. These tools are called Object-Relational Mapping (ORM) tools since they are data storage subsystems based on relational databases. However, they also work well with modern non-relational storage classified as NoSQL databases (such as MongoDB and Azure Cosmos DB) since their data model is closer to the target object model than a purely relational model.
13:8
ORMs improve and simplify the whole development process since they factor out and take away the burden of mapping data into objects and vice versa, so developers can focus just on the peculiarity of the business domain.
13:9
In this chapter, we will cover the following topics:
13:10
13:11
Understanding ORM basics
13:12
Configuring Entity Framework Core
13:13
Entity Framework Core migrations
13:14
Compiled models
13:15
Querying and updating data with Entity Framework Core
13:16
Deploying your data layer
13:17
Understanding Entity Framework Core advanced features
13:18
13:19
This chapter describes ORMs and how to configure them, and then focuses on Entity Framework Core, the ORM included in .NET 8.
13:20
Before delving into ORM basics, let’s look at the technical requirements needed to follow the practical examples in this chapter.
13:21
Technical requirements
13:22
This chapter requires the free Visual Studio 2022 Community Edition or better with all the database tools installed.
13:23
All the concepts in this chapter will be clarified with practical examples. You will find the code for this chapter at https://github.com/PacktPublishing/Software-Architecture-with-C-Sharp-12-and-.NET-8-4E.
13:24
Understanding ORM basics
13:25
ORMs map relational DB tables into in-memory collections of objects where object properties correspond to DB table columns. Types from C#, such as Booleans, numeric types, and strings, have corresponding DB types. If GUIDs are not available in the mapped DB, then types such as GUIDs are mapped to their equivalent string representations. All date and time types are mapped either to C# DateTime when the date/time contains no time zone information, to DateTimeOffset when the date/time also contains explicit time zone information, to DateOnly when the type contains just date information, or to TimeOnly when the type contains just time information. Any DB time duration is mapped to a TimeSpan. Finally, single characters should not be mapped at all to DB fields.
13:26
Since the string properties of most object-oriented languages have no length limits associated with them (while DB string fields usually have length limits), the DB limits are taken into account in the DB mapping configuration. In general, when the mapping between DB types and object-oriented language types needs options to be specified, these options are declared in the mapping configuration.
13:27
The way the whole configuration is defined depends on the specific ORM. Entity Framework Core offers three options:
13:28
13:29
Data annotations (property attributes)
13:30
Name conventions
13:31
A fluent configuration interface based on configuration objects and methods
13:32
13:33
While the fluent interface can be used to specify any configuration option, the data annotations and name conventions can be used for a smaller subset of them.
13:34
Personally, I prefer using the fluent interface for most settings. I use name conventions only for specifying the principal key with an ID property name since I find that relying on name conventions for more complex settings is very dangerous. In fact, there are no compilation-time checks on name conventions, so a re-engineering operation might erroneously change or destroy some ORM settings.
13:35
I use data annotations mainly for specifying constraints on the possible values of properties, such as the maximum length of a value or the fact that a property is obligatory and can’t be null. In fact, these constraints restrict the type specified in each property, so placing them next to the properties they are applied to increases the code’s readability.
13:36
All other settings are better grouped and organized by using the fluent interface in order to increase code readability and maintainability.
13:37
Each ORM adapts to a specific DB type (Oracle, MySQL, SQL Server, and so on) with DB-specific adapters called providers or connectors. Entity Framework Core has providers for most of the available DB engines.
13:38
A complete list of providers can be found at https://docs.microsoft.com/en-US/ef/core/providers/.
13:39
Adapters are necessary for the differences in DB types, for the way transactions are handled, and for all other features that are not standardized by the SQL language.
13:40
Relationships among tables are represented with object pointers. For instance, in a one-to-many relationship, the class that’s mapped to the one side of the relationship contains a collection that is populated with the related objects on the many side of the relationship. On the other hand, the class mapped to the many side of the relationship has a simple property that is populated with a uniquely related object on the one side of the relationship.
13:41
While, in the case of a one-to-one relationship, both classes have a property populated with the companion object, in the case of many-to-many relationships, both classes contain a collection that is populated with the related objects.
13:42
The whole database (or just a part of it) is represented by an in-memory cache class that contains a collection for each mapped DB table. First, the query and update operations are performed on an instance of an in-memory cache class, and then this instance is synchronized with the database.
13:43
The in-memory cache class that’s used by Entity Framework Core is called DbContext and it also contains the mapping configuration.
13:44
Developers can customize the DbContext class furnished by Entity Framework Core by inheriting from it and by adding their database-mapping instructions inside overridden methods.
13:45
Summing up, DbContext subclass instances contain partial snapshots of the DB that are synchronized with the database to get/update the actual data.
13:46
DB queries are performed with a query language made of method calls on the collections of the in-memory cache class. The actual SQL is created and executed during the synchronization stage. For instance, Entity Framework Core performs Language Integrated Query (LINQ) queries on the collections mapped to the DB tables.
13:47
In general, LINQ queries produce IEnumerable instances, that is, collections whose elements are not computed when the is created at the end of the query, but when you actually attempt to retrieve the collection elements from the. This is called lazy evaluation or deferred execution. It works as follows:
13:48
13:49
LINQ queries that start from a mapped collection of a DbContext create a specific subtype of IEnumerable called IQueryable.
13:50
An IQueryable contains all the information that’s needed to issue a query to the database, but the actual SQL is produced and executed when the first element of the IQueryable is retrieved.
13:51
Typically, each Entity Framework query ends with a ToListAsync or ToArrayAsync operation that transforms the IQueryable into a list or array, thereby causing the actual execution of the query on the database.
13:52
If the query is expected to return just a single element or no element at all, we typically execute a SingleOrDefaultAsync operation that returns a single element, if any, or null. This operation may be used also when several results are expected but we need just one. In this case, we might also use LastOrDefaultAsync.
13:53
If we need just to count the total results, for instance, for adequately organizing paging information, we can use CountAsync().
13:54
13:55
Also, updates, deletions, and the addition of new entities to a DB table are performed by mimicking these operations on a DbContext collection property that represents the database table. However, entities may only be updated or deleted this way after they have been loaded in that memory collection by means of a query. Typically, an update query requires the in-memory representation of the entity to be modified as needed, while a delete query requires the in-memory representation of the entity to be removed from its in-memory mapped collection. In Entity Framework Core, the removal operation is performed by calling the Remove(entity) method of the collection.
13:56
The addition of a new entity has no further requirements. It is enough to add the new entity to the in-memory collection. Updates, deletions, and additions that are performed on various in-memory collections are actually passed to the database with an explicit call to a DB synchronization method.