Enlisting in Ambient transactions is not supported using TransactionScope in asp.net core 2 app - ado.net

When opening sql connection inside TransactionScope its giving "Enlisting in Ambient transactions is not supported" error. I am using ado.net in asp.net core 2 app.
using (var ts = new TransactionScope())
{
try
{
Connection.Open();
repository.Insert(entity);
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
finally
{
Connection.Close();
}
}

If you encounter this problem when using .Net Standard, you can add a recent reference to System.Data.SqlClient and this problem will go away.

Replace the PackageReference to Microsoft.AspNetCore.All with the individual package references, and then add a PackageReference to "System.Data.SqlClient", Version="4.3.1".
Here is the link to the solution (for reference) that worked for me (Dapper is throwing System.Data.SqlClient.SqlConnection exception after upgrading System.Data.SqlClient to version 4.5.0-preview2).
This worked for System.Data.SqlClient Version up to 4.3.1., 4.4.0 and above gives the same error.

Related

Can't create SqlParameter in EF Core 3.1.2 in Xamarin.Android application

I have Android Xamarin.Forms project. It depends on Db project with EF Core code (SQL Server) and targeted .Net Standard 2.0. Both projects in one solution.
With EF Core 2.2.6 everything works fine. When I switch to EF Core 3.1.2, the project does not work anymore.
I made the following changes to compile it:
I added Microsoft.Data.SqlClient 1.1.1 nuget project reference and use namespace Microsoft.Data.SqlClient instead of System.Data.SqlClient
Replace DbSet<Entitiy>.FromSql calls with DbSet<Entitiy>.FromSqlRaw
When I create SqlParameter and try to access it I get an error.
E.g. when I run the following code:
try
{
var sqlParam = new SqlParameter("aaa", "bbb");
var value = sqlParam.Value; // exception thrown here
}
catch (Exception ex)
{
Debug.WriteLine($"Exception: {ex.GetType()}");
Debug.WriteLine($"Message: {ex.Message}");
Debug.WriteLine($"StackTrace: {ex.StackTrace}");
}
I get the following error messages:
Exception: System.NullReferenceException
Message: Object reference not set to an instance of an object
StackTrace: at Microsoft.Data.SqlClient.SqlParameter.get_Value () [0x00000] in E:\SqlClientInternal\agent-1_work\5\s\src\Microsoft.Data.SqlClient
etcore\ref\Microsoft.Data.SqlClient.cs:1222
at [0x00012] in .cs:100
When the sqlParam just assigned, and I want to view its value, I get the following view in Visual Studio:
I use Visual Studio 2019, I tried 16.3.4 and the latest as for now 16.4.6.
How to fix this issue? What is wrong with my code?

EF Core tools System.Configuration.ConfigurationManager assembly not found

I am creating a new application that is using EF Core 2 with migrations.
The application itself is .net Framework but the model is in a separate .net core 2.0 assembly. Everything is working fine I have defined a designtime context factory:
public class MyDesignTimeContextFactory : IDesignTimeDbContextFactory<MyContext>
{
public MyContext CreateDbContext(string[] args)
{
return new MyContext("Server=localhost\\SQLEXPRESS;Database=DBName;User ID=Test;Password=0000;");
}
}
And I can generate migrations and apply/revert them to the DB.
Now if I replace hardcoded connection string with a call to config file
return new MyContext(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionString");
I have an error when calling EF Core tools:
Add-Migration -Project MyProject.Model -Name Initialization
System.IO.FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.1.0 ....,
However the nuget is there and I can access ConfigurationManager in ContextFactory (not the designtime one) with no problem when launching the application itself. Looks like EF core tools are not looking for the dependencies of the model assembly...
Is there something I am missing? Maybe it is not possible to use ConfigurationManager in DesignTime context factory?
Finally the problem was in the application project. I had to add the nuget package for System.Configuration.ConfigurationManager to the .Net Framework app so the PackatManager can find it. A bit weired that it works at runtime but not in "design mode".

FluentNhibernate, Nhibernate.Search and Lucene.Net version

I created a project, and used NuGet to install Nhibernate.Search. During the installation NuGet also downloads the Lucene.Net for me.
With NuGet I have following packages downloaded and installed
FluentNHibernate.dll: 1.3.0733
NHibernate.dll: 3.3.1.4000
NHibernate.Search.dll: 2.0.2.4000
Lucene.Net.dll: 2.9.4.1
All the dependencies are managed by NuGet. But when I ran following codes
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Search.Event;
using NHibernate.Search.Store;
namespace Test {
public class NHibernateSearchSessionProvider {
private static ISessionFactory sessionFactory;
private static object syncRoot = new object();
public static ISessionFactory SessionFactory {
get {
lock (syncRoot) {
if (sessionFactory == null) {
sessionFactory = createSessionFactory();
}
return sessionFactory;
}
}
}
private static ISessionFactory createSessionFactory() {
var config = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("HomeDB"))
)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserAccountMap>())
.BuildConfiguration();
// Add NHibernate.Search listeners
config.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
config.SetProperty("hibernate.search.default.indexBase", "~/LuceneIndex");
return config.BuildSessionFactory();
}
}
}
An exception message Could not load file or assembly 'Lucene.Net, Version=2.9.2.2, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
It looks like this version of NHibernate.Search is still using Lucene.Net 2.9.2.2 not the new one. I can always manually fix all the dependencies, but I prefer to use NuGet.
Anybody has experience how shall I do to make code work?
Thanks for any suggestion
This looks like a configuration error for the NHibernate.Search nuget package, it states that it supports Lucene.Net 2.9.2.2 and up. Try modifying your packages.config file to use the 2.9.2.2 version of Lucene (instead 2.9.4.1) and nuget will use the specified version during package restoration.
You will probably need to clean out your bin-folder to remove the "old" 2.9.4.1 assembly.
use Install-Package NHibernate.Search.MB
I tried to fix it but it did not.
Already Nhibernate.Search very old

Entity Framework 5.0 RC - Package Manager command 'add-migration' fails due to supposedly missing configuration type

Using Entity Framework 5.0.0 RC/EF 5.x DbContext Generator for C#/Visual Studio 2012 RC/.NET 4.0, I'm trying to enable automatic migrations in my project. I've run enable-migrations in the Package Manager Console:
PM> enable-migrations
No classes deriving from DbContext found in the current project.
Edit the generated Configuration class to specify the context to enable migrations for.
Code First Migrations enabled for project Test.
As you can see, it didn't automatically detect my DbContext derived type, but I solved this easily enough by entering the name of this type in the generated code file, Migrations/Configuration.cs.
However, the next step, the Package Manager Console command enable-migrations fails due to not finding the migrations configuration type added by the previous step.
PM> add-migration Initial
No migrations configuration type was found in the assembly 'Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
How can I solve this?
EDIT: I found that I could specify the name of the configuration type with the parameter -ConfigurationTypeName:
PM> add-migration -ConfigurationTypeName Test.Migrations.Configuration Initial
The type 'Configuration' is not a migrations configuration type.
This still doesn't work, but at least it elucidates why add-migration bails, i.e. it thinks Test.Migrations.Configuration isn't a migrations configuration type. Does anyone have a clue as to why it isn't accepted, given that it was generated by enable-migrations? See the generated code below for reference (UserModelContainer derives from DbContext):
namespace Test.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Test.Models;
internal sealed class Configuration : DbMigrationsConfiguration<UserModelContainer>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(UserModelContainer context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
The issue turned out to be that I had installed Entity Framework 5.0.0 RC while targeting .NET framework 4.5. Due to deploying to Windows Azure, I found I had to target .NET 4.0 instead. I don't know the intricacies of NuGet, but it seems that the EF package installed for .NET 4.5 didn't work properly with my 4.0 targeting project.
After reinstalling the EF NuGet package, while targeting my project at .NET 4.0, everything works well.

MEF - Migration from .NET 3.5 to .NET 4.0

I've got an easy sample from the internet that works fine in the .NET 3.5 framework using System.ComponentModel.Composition.dll version v2.0.50727
I've changed the project definition and changed the target to .NET 4.0 and it works perfect.
When I replace the v2.0.50727 version of the above .dll to the latest version which is v4.0.30319 I get an error that complains during the composition of the container. The code where it break is as follows:
private void LoadPlugins() {
var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ExportsChanging += new EventHandler(container_ExportsChanging);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch); // throws Exception
}
And the exception is the following:
System.ComponentModel.Composition.ChangeRejectedException was unhandled
Message=The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) More than one export was found that matches the constraint '((exportDefinition.ContractName == "MefTutorial.IPlugin") AndAlso (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") AndAlso "MefTutorial.IPlugin".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))'.
Resulting in: Cannot set import 'MefTutorial.PluginConsumer._myPlugins (ContractName="MefTutorial.IPlugin")' on part 'MefTutorial.PluginConsumer'.
Element: MefTutorial.PluginConsumer._myPlugins (ContractName="MefTutorial.IPlugin") --> MefTutorial.PluginConsumer
What do I need to do to migrate to the .NET 4.0 concerning MEF?
Could it be that another project still references the .net 3.5 version? The error message says that there are two exports of type IPlugin, which I'm quite certain of means that finds both the 3.5 and 4.0 version of the dll.
Check that only the 4.0 version of MefTutorial is referenced and/or present.
OK, I found the problem. Apparently in the previous version the notation was as mentioned in my previous comment, but in the new .NET 4.0 version the syntax for import should be:
code>
[ImportMany(typeof(IPlugin))]
internal List _myPlugins { get; set; }
Notice the use of List and ImportMany instead of IList and Import.