I am not fan of any frameworks specially all that Javascript, HTML frameworks. Entity Framework makes development faster for sure, mapping data models to object models is easy and it saves a lot of time. Also, it magically queries the database for you and fills your objects. All sounds good but there are problems with it too specially if you care about your database's performance. Quality of Entity Framework's queries has been a problem for long time. It's not easy to debug Entity Framework queries, these queries give nightmares to DBAs.
In SQL Server, poor quality queries cost you performance. In Cosmos DB, poor quality queries will cost you money! When you realize, you cannot run stored procedures or use a trigger with EF might be too late for you to stop using EF.
After all the warnings. If you still want to use Entity Framework, keep reading 😊 First you need to download the Nuget package of EF for Cosmos (Microsoft.EntityFrameworkCore.Cosmos)
After the installation, you need to create your Model/s. I will use the following sample model to store in Azure Cosmos DB Emulator.
Next step is to create DBContext class. This class is responsible to communicate to Cosmos DB. I get the url and key information from the Cosmos DB Emulator.
We need to do more customization to make this work. We need to specify the partition key of Orders Container. To do that, we need to override OnModelCreating function. I made the Orders container my default container by using HasDefaultContainer method.
We are done with configuration, Orders Database has not been created. You might want to create that manually or let EF creates it for you if it doesnt exist. You can do that by the following code.
We are ready to save data to Azure Cosmos DB. In the following example, I create data for Order object and send it to Azure Cosmos DB by using Entity Framework.
After I run this code, I can see the data in my dataabase.
How about reading this data? Here is an example.
It is easy, but easy does not mean this is the right way to do this. As you can see, there is no information about how much Request Unit this query costed you. OrderId is not your partition id and if this query is one of your common queries, you might need more Request Units and EF does not give you any information about the cost. May be later, you might discover stored procedures or triggers and you may want to use them. But you picked EF, and it does not support many functions of Cosmos DB. What are you going to do? You are stuck. How are you going to tell that to your boss? I recommend you to use one of Cosmos DB's SDKs or REST API if you don't want to be stuck!
Hi,
ReplyDeleteCan we mix it with SQL Azure and create a Transaction then have a command to do something with a SQL also and then Commit or Rollback both with a same SaveChange ?