Page 13 - MSDN Magazine, March 2019
P. 13

doesn’t need a sub-document to have a foreign key back with its parent. However, the EF Core logic for persisting owned entities does require the foreign key (handled by EF Core Shadow Prop- erties) in order to persist owned entities in relational databases. Therefore, it leverages its existing logic to infer the ShipId property within the Origin sub-document.
EF Core also has the ability to map owned collections with the OwnsManymapping.Inthiscase,you’dseemultiplesub-documents within the parent document in the database.
There’s a gotcha that will be fixed in EF Core 3.0.0 preview 2. EF Core currently doesn’t understand null owned entity properties. The other database providers will throw a runtime exception if you attempt to add an object with a null owned entity property, a behavior you can read about in the previously mentioned April 2018 column. Unfortunately, the Cosmos DB provider doesn’t prevent you from adding objects in this state, but it’s not able to materialize objects that don’t have the owned entity property populated. Here’s the exception that was raised when I encountered this problem:
"System.InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'."
So if you see that error when trying to query entities that have owned type properties, I hope you’ll remember that it’s likely a null owned type property causing the exception.
Logging the Provider Activity
EF Core plugs into the .NET Core logging framework, as I covered in my October 2018 column (msdn.com/magazine/mt830355). Shortly after that article was published, the syntax for instantiating the LoggerFac- tory was simplified, although the means of using categories and log levels to determine what should get output in the logs didn’t change. I reported the updated syntax in a blog post, “Logging in EF Core 2.2 Has a Simpler Syntax—More Like ASP.NET Core” (bit.ly/2UdSkuI).
When EF Core interacts with the Cosmos DB provider, it also shares details with the logger. This means you can see all of the same types of information in the logs that you can with other providers.
Keep in mind that CosmosDB doesn’t use SQL for inserting, updating and deleting, as you’re used to doing with relational databases. SQL is used for queries only, so SaveChanges won’t show SQL in the logs. However, you can see how EF Core is fixing up the objects, creating any needed IDs, foreign keys and discrimi- nators. I was able to see all of this information when logging all of the categories tied to the Debug LogLevel, rather than only filter- ing on the database commands.
Here’s how I configured my GetLoggerFactory method to do that. Notice the AddFilter method. Rather than passing a category into the first parameter, I’m using an empty string, which gives me every category:
private ILoggerFactory GetLoggerFactory() {
IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(builder =>
builder.AddConsole()
.AddFilter("" , LogLevel.Debug));
return serviceCollection.BuildServiceProvider() .GetService<ILoggerFactory>();
}
If I’d wanted to filter on just the SQL commands, I’d have passed DbLoggerCategory.Database.Command.Name to give the correct msdnmagazine.com
string for just those events instead of an empty string. This relayed a lot of logging messages when inserting a few graphs and then executing a single query to retrieve some of that inserted data. I’ll include the full output and my program in the download that ac- companies this column.
Some interesting tidbits from those logs include this information about adding shadow properties where you can, in the case of this provider,seethespecialDiscriminatorpropertybeingpopulated:
dbug: Microsoft.EntityFrameworkCore.Model[10600]
The property 'Discriminator' on entity type 'Station' was created
in shadow state because there are no eligible CLR members with a matching name.
If you’re saving data, after all of that fix-up is performed, you’ll see a log message that SaveChanges is starting:
debug: Microsoft.EntityFrameworkCore.Update[10004] SaveChanges starting for 'ExpanseContext'.
This is followed by messages about DetectChanges being called. The provider will use internal API logic to add, modify or remove the document in the relevant collection, but you won’t see any par- ticular logs about that action. However, after these actions complete, the logs will relay typical post-save steps such as the context updating the state of the object that was just posted:
dbug: Microsoft.EntityFrameworkCore.ChangeTracking[10807]
The 'Consortium' entity with key '{ConsortiumId: a4b0405e-a820-4806-
8b60-159033184cf1}' tracked by 'ExpanseContext' changed from 'Added' to 'Unchanged'.
If you’re executing a query, you’ll see a number of messages as EF Core works out the query. EF Core starts by compiling the query and then massages it until it arrives at the SQL that gets sent to the database. Here’s a log message showing the final SQL:
dbug: Microsoft.EntityFrameworkCore.Database.Command[30000] Executing Sql Query [Parameters=[]]
SELECT c
FROM root c
WHERE (c["Discriminator"] = "Consortium")
Waiting for Release
The EF Core Cosmos DB provider preview is available for EF Core 2.2+. I worked with EF Core 2.2.1 and and then, in order to see if I noticed any changes, switched to the unreleased EF Core packages in the latest preview of EF Core 3, version 3.0.0-preview.18572.1.
EF Core 3 is on the same release schedule as .NET Core 3.0, but the latest information about the timing only says “sometime in 2019.” The official release of Preview 2 was announced at the end of January 2019 in the blog post at bit.ly/2UsNBp6. If you’re interested in this support for Azure Cosmos DB, I recommend trying it out now and helping the EF team uncover any problems to make it a more viable provider for you when it does get released. n
Julie lerman is a Microsoft Regional Director, Microsoft MVP, software team coach and consultant who lives in the hills of Vermont. You can find her presenting on data access and other topics at user groups and conferences around the world. She blogs at the thedatafarm.com/blog and is the author of “Programming Entity Framework,” as well as a Code First and a DbContext edition, all from O’Reilly Media. Follow her on Twitter: @julielerman and see her Pluralsight courses at juliel.me/PS-Videos.
Thanks to the following Microsoft technical expert for reviewing this article: Andriy Svyryd
March 2019 9


































































































   11   12   13   14   15