How to get current transaction from the dbcontext - .net-core

In Entity Framework 6, under the DbContext class you can get to current transaction by context.Database.CurrentTransaction. However this API doesn't seem like available in EF.Core. How can I retrieve current transaction object from a dbcontext in EF.Core?

EF Core still lacks many EF6 features, but (slowly) is catching up.
In that regard, I can't say for earlier versions, but in the latest (so far ) v1.1.0 the DbContext.Database CurrentTransaction property is there, so you can use the same code as in EF6 to access it.

Related

ASP .NET Boilerplate + MongoDb

I am using ASP.Net boilerplate framework + SQL Server 2016 in my project. Recently I have faced a challenge with migration from SQL Server to MongoDB. I have found that it is possible with ASP .NET boilerplate and installed required NuGet packages, however, due to the lack of documentation the only thing I have managed to do is to define respective RepositoryBase class:
public abstract class MyRepositoryBase<TEntity, TPrimaryKey> : MongoDbRepositoryBase<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
protected MyRepositoryBase(IMongoDatabaseProvider databaseProvider)
: base(databaseProvider)
{
}
}
As far as I understand, first of all, I need to define connection string somewhere now. And then populate the database with required basic data(which previously had been done by EF Core migrations). Obviously, EF Core in the new approach is obsolete so does that mean for my DbContext class that it is obsolete as well?
Actually, there are plenty of questions in relation to ASP .NET boilerplate and MongoDB integration, therefore my current post is actually a request for provision of some kind of example of the existing integration. Thank you in advance.
You can register your module by depending on it on your web module.
[DependsOn(typeof(YourMongoDbModule))]
public class YourWebModule : AbpModule
{
}
I think you have to register the repository with:
IocManager.Register(typeof(IMongoRepository<>), typeof(MongoRepository<>), Abp.Dependency.DependencyLifeStyle.Singleton);
You can refer this sample.
Look at this comment also.
Here is a framework which maps EF Core to Mongo DB.

Precompiling (creating a mapping?) EF DbContext for faster debugging

It takes a while (3 minutes+) to 'create/compile' my DbContext. The web server starts in about 5 seconds, but when I do the first query to my database, Entity Framework has to 'build/create/compile' the database in memory or something, I think? The next requests are almost instant. This was a Database First creation of the DbContext, the database already exists in MSSQL and has data. The DbContext contains about 500 DbSet's with relations.
Is there a way to speed this up by doing the 'creation(mapping?)' of my Entity Framework's DbContext before running the web server, create the file/mappings it needs, so the first request is fast too?
EDIT1:
I've tried the Power Tools, but they give me an error that the DbContext has no constructor that can be used, while it has a normal constructor
public DbContext() : base() {}
Any other things I could try?
The Entity Framework documentation describes how to generate views using EF Power Tool here.
Once you have in stalled EF Power Tools you have to:
Right click on the class containing your DbContext or on your .edmx file
Select "Generate Views"
This will generate the class containing the pre-computed mapping, which will automatically load on startup. If you change your database and don't regenerate the views EF will throw an exception.
Whether it will work for EF7 though, who knows...

EntityFramework 7 - CodeFirst - SQLite - Manage DB using ApplyMigrations at runtime

I am well on my way to utilizing EF7 CodeFirst with SQLite...but really want to employ DB Migrations at runtime. This is a desktop application (Click-once deployment) meant to sync with a main database when connection is available, and provide offline data when no connection is present.
I have pulled down the nuget pre-release versions and all is working, except I cannot find any documentation of how to apply the migrations at runtime. I can successfully Add-Migrations and manually Apply-Migrations...but need a way to programatically Apply-Migrations at runtime.
I've also browsed the EF7 open-source project, but could not get anywhere there.
Versions I'm using: Latest Pre-release as of 9/15/2015
EntityFramework.Sqlite v7.0.0-beta7
EntityFramework.Relational v7.0.0-beta7
EntityFramework.Commands v7.0.0-beta7
...et al...you get the picture.
I am asking for help to apply runtime migrations...or what is the documented/recommended path for programatically maintaining a local/embedded db using EF7 CodeFirst SQLite?
UPDATE:
I went back to EF6 with SQLite but then found out that there is not SQLMigrationGenerator for SQLite.
EDIT:
I believe ApplyMigrations() method referenced in one of the notes has been deprecated. Searching the repository, there is no reference to "ApplyMigrations".
Today you can invoke the extension method Migrate on the DatabaseFacade.
This method is only available when the using Microsoft.Data.Entity statement is present. It comes from the RelationalDatabaseFacadeExtensions class that is part of the EntityFramework.Relational package.
Still have to find out how to migrate up and down from the API.

Can you create a database without migrations in EF5?

I am following the offical asp.net "Getting started with EF 5 using MVC 4". In that tutorial, the database is created when the migrations are performed(in my understanding). When I was looking at the EF 5 with Mvc 5 tutorial they didn't use migrations to create a database. They use database initializer. So, I was wondering could create a database for your project without using migrations in EF 5? Also, what would the difference be with both these approaches?
Code first Migrations and using Package Manager Console Commands to do upgrades can get a bit confusing at first.
You can use the initializer to CreateDatabaseIfNotExists , DropCreateIfModelChanges, DropCreateDatabaseAlways and to MigrateDatabaseToLatestVersion
See the interface IDatabaseInitializer<TContext>.
CreateDatabaseIfNotExists // is the Default initializer.
So this is why it appears EF just does things for you sometimes.
So the answer is "YES you can "Create a Database without Migrations"
But the difference is not obvious and if you would do that long term is another question.
If you are using migrations. It would Update the Db to match the code first model.
If there is NO database, then that means creating the database.
So Thats why Automated migrations and CreateDB look confusing since they can result in same outcome sometimes. But technically they are different.
So generally it is sufficient to use code first automatic "migrations" only.
Migrations can be either Automatic or "managed".
The managed migrations approach invovles generating code , tweaking the code and running PM commandlet or POwershell command to actually perform the migration.
With Automated migrations you just need set the intitializer and Access the DBContext.
There are 2 parts to the process.
a) The DB Initializer step.
do this immediately before instantiating YourDBContext.
//eg
// DONT TOUCH MY DB or i break your back!
Database.SetInitializer(new ContextInitializerNone<YourDbContext>()); // Do Nothing,
// OR
// yes migrate my db to match my code please.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourDbContext, YourMigrationConfiguration>()); // Set to migration is requested, see config class below
The Confirguration class specified when using Migration initializer looks like this
public class YourMigrationConfiguration<TContext> : DbMigrationsConfiguration<TContext>
where TContext : DbContext{
protected YourMigrationConfiguration() {
AutomaticMigrationsEnabled = true; // run it when needed. Do not wait for my PM Command
AutomaticMigrationDataLossAllowed = true; // if the new db look means dropping tables or columns go ahead and kill my data. So use this option with caution.
}
then just trigger the migration in code when required.
Context.Database.Initialize(true); // i place this inside a method on my UoW class
Code first Db initialization strategies.
Code first migrations recommended reading
Managed Migrations
There are many articles on the web on this topic.

System.InvalidOperationException: Mapping and metadata information could not be found for EntityType

I have an ASP.NET 4.0 web application that uses Entity Framework 4.3.1 and Self-Tracking Entities. It works fine until I add another ADO.NET Entity Data Model (.edmx) file to it. After that the project compiles without any errors, but as soon as it calls a self-tracking entity object, the application produces the System.InvalidOperationException: Mapping and metadata information could not be found for EntityType 'namespace.classname'.
I have tried adding the second ADO.NET Entity Data Model into a different namespace - but that does not help.
If I remove the added .edmx file from the project, the problem disappears.
If I remove the Self-tracking entity files (Model.tt and Model.Context.tt), the problem disappears.
It looks like Self-Tracking Entities cannot function properly when there is more than Entity Data Model.
Has anyone else experienced and solved this problem?
Make sure to use consistent Context generation throughout your solution.
Use the EF 5.x DbContext Generator on each of your Entity Data Models. You can either download the template via the ExtensionManager (search for EF 5.x) or here
I think self tracking entities are not supported from 4.1 (DbContext) onwards.
We had a few problems at work when upgrading from 4 to 4.2 with ste and we ended up reworking all to use DbContext and getting rid of ste. Since then it works like a charm!

Resources