Connect to an IBM DB2 database from ASP.NET Core

1

I need to access an AS400 db2 database from an ASP .Net 5 or Core application.

Try with entity framework through the following packages

link

Following the documentation on this page:

link

But it did not work, I presented errors of the supplier, I do not know if I was doing things correctly, if they have an example it would be great.

Ultimately I would use classic ADO, I add the used code.

project.json

"dependencies": {
"EntityFramework.IBMDataServer": "7.0.0-beta1",
. . .

},

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddViews()
            .AddRazorViewEngine();

        services.AddEntityFramework()
            .AddDb2()
            .AddDbContext<DB2.Models.Users.UserContext>();

        services.AddScoped<IUserRepository, UserRepository>();
    }

User.cs

using System.ComponentModel.DataAnnotations;

namespace DB2.Models.Users
{
    public class User
    {
        [Key]
        public string CODCOL { get; set; }
        public string CLACOL { get; set; }
    }
}

UserContext.cs

using Microsoft.Data.Entity;
using IBM.Data.Entity;

namespace DB2.Models.Users
{
    public class UserContext: DbContext
    {
        public DbSet<User> User { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseDb2(@"Server=x;Database=x;password=x;uid=x;");
            base.OnConfiguring(optionsBuilder);
        }        
    }
}

UserRepository.cs

using System.Linq;

namespace DB2.Models.Users
{
    public class UserRepository: IUserRepository
    {
        private UserContext _context;

        public UserRepository(UserContext context)
        {
            _context = context;
        }

        public void pass()
        {
            var x = _context.User.First();           
        }
    }
}

Compile perfectly, once I execute it, I see an error in the line:

System.IO.FileNotFoundException was unhandled by user code
  FileName=IBM.Data.DB2, Version=9.7.4.4, Culture=neutral, PublicKeyToken=7c307b91aa13d208
  FusionLog==== Pre-bind state information ===
LOG: DisplayName = IBM.Data.DB2, Version=9.7.4.4, Culture=neutral, PublicKeyToken=7c307b91aa13d208
 (Fully-specified)
LOG: Appbase = file:///C:/Users/JOlivas/.dnx/runtimes/dnx-clr-win-x86.1.0.0-rc1-update1/bin/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: IBM.Data.DB2, Version= 9.7.4.4, Culture= neutral, PublicKeyToken= 7c307b91aa13d208
LOG: Fusion is hosted.Check host about this assembly.
LOG: Try host assembly store with assembly ibm.data.db2, version= 9.7.4.4, culture= neutral, publickeytoken= 7c307b91aa13d208, processorarchitecture= x86.
LOG: Try host assembly store with assembly ibm.data.db2, version= 9.7.4.4, culture= neutral, publickeytoken= 7c307b91aa13d208, processorarchitecture= msil.
LOG: Try host assembly store with assembly ibm.data.db2, version= 9.7.4.4, culture= neutral, publickeytoken= 7c307b91aa13d208.
WRN: Host assembly store does not contain this assembly.
LOG: Attempting download of new URL file:///C:/Users/JOlivas/.dnx/runtimes/dnx-clr-win-x86.1.0.0-rc1-update1/bin/IBM.Data.DB2.DLL.
LOG: Attempting download of new URL file:///C:/Users/JOlivas/.dnx/runtimes/dnx-clr-win-x86.1.0.0-rc1-update1/bin/IBM.Data.DB2/IBM.Data.DB2.DLL.
LOG: Attempting download of new URL file:///C:/Users/JOlivas/.dnx/runtimes/dnx-clr-win-x86.1.0.0-rc1-update1/bin/IBM.Data.DB2.EXE.
LOG: Attempting download of new URL file:///C:/Users/JOlivas/.dnx/runtimes/dnx-clr-win-x86.1.0.0-rc1-update1/bin/IBM.Data.DB2/IBM.Data.DB2.EXE.

  HResult=-2147024894
  Message=Could not load file or assembly 'IBM.Data.DB2, Version=9.7.4.4, Culture=neutral, PublicKeyToken=7c307b91aa13d208' or one of its dependencies.The system cannot find the file specified.
 Source=EntityFramework.IBMDataServer
 StackTrace:
       at IBM.Data.Entity.Storage.Internal.Db2SqlConnection.CreateDbConnection()
       at Microsoft.Data.Entity.Internal.LazyRef'1.get_Value()
       at Microsoft.Data.Entity.Storage.RelationalConnection.Open()
       at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
       at System.Linq.Enumerable.WhereSelectEnumerableIterator'2.MoveNext()
       at System.Linq.Enumerable.First[TSource](IEnumerable'1 source)
       at lambda_method(Closure , QueryContext )
       at Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_1'1.<CompileQuery>b__1(QueryContext qc)
       at Microsoft.Data.Entity.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
       at Microsoft.Data.Entity.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
       at System.Linq.Queryable.First[TSource](IQueryable'1 source)
       at DB2.Models.Users.UserRepository.pass() in D:\Proyectos\MVC\NSEL\DB2\src\DB2\Models\Users\UserRepository.cs:line 16
       at DB2.Controllers.HomeController.test() in D:\Proyectos\MVC\NSEL\DB2\src\DB2\Controllers\HomeController.cs:line 33
  InnerException: 

(Update) Install the driver: IBM Data Server Driver Package and show me an error different from the previous one

IBM.Data.DB2.DB2Exception was unhandled by user code
ErrorCode=-2147467259
HResult=-2147467259
Message=ERROR [08001] [IBM] SQL30081N  A communication error has been detected. Communication protocol being used: "TCP/IP".  Communication API being used: "SOCKETS".  Location where the error was detected: "192.168.128.5".  Communication function detecting the error: "connect".  Protocol specific error code(s): "10061", "*", "*".  SQLSTATE=08001

Source=IBM.Data.DB2
StackTrace:
    at IBM.Data.DB2.DB2ConnPool.Open(DB2Connection connection, String& szConnectionString, DB2ConnSettings& ppSettings, Object& ppConn)
    at IBM.Data.DB2.DB2Connection.Open()
    at Microsoft.Data.Entity.Storage.RelationalConnection.Open()
    at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
    at System.Linq.Enumerable.WhereSelectEnumerableIterator'2.MoveNext()
    at System.Linq.Enumerable.First[TSource](IEnumerable'1 source)
    at lambda_method(Closure , QueryContext )
    at Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_1'1.<CompileQuery>b__1(QueryContext qc)
    at Microsoft.Data.Entity.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
    at Microsoft.Data.Entity.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
    at System.Linq.Queryable.First[TSource](IQueryable'1 source)
    at DB2.Models.Users.UserRepository.pass() in D:\Proyectos\MVC\NSEL\DB2\src\DB2\Models\Users\UserRepository.cs:line 16
    at DB2.Controllers.HomeController.test() in D:\Proyectos\MVC\NSEL\DB2\src\DB2\Controllers\HomeController.cs:line 33
InnerException:
    
asked by Jonhy.Olivas 01.04.2016 в 23:22
source

1 answer

1

In ASP.NET Core a new version of EF (EF Core) is also used, which for now supports few database engines but surprisingly if it has DB2 for databases (here you have the documentation)

In this same documentation you have this link to an example application where they explain step by step how to work with an IBM database.

If you look at this example code, you will see that in the OnConfiguring method in the class IBMDbContext the database you want to access is configured

class IBMDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseDb2(@"Server=servername:portno;Database=dbname;userid=uid;password=pwd");
    }
    ...
}   

Actually, the configuration of the connection should not be made there but in the ConfigureServices of the class Startup doing something like that (I'm not 100% sure it works because I have not tried it but it's how it's done with SqlServer or Sqlite):

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Add EF services to the services container.
    services.AddEntityFramework()
        .UseDb2()
        .AddDbContext<ApplicationDbContext>(options => 

             options.UseDb2(Configuration["Data:DefaultConnection:ConnectionString"]));
    ...
} 

By the way, of the two NuGuet packages you have put, you have to use the second one ( EntityFramework.IBMDataServer 7.0.0 -beta1 ) because the first one is for EF6

Update (04/04/2016):

If an error occurs with the Could not load file or assembly 'IBM.Data.DB2, Version=9.7.4.4, Culture=neutral, PublicKeyToken=7c307b91aa13d208' ... message, it could indicate that the Driver for .NET "IBM Data Server Driver Package (Windows AMD64 and Intel EM64T) Version 10.5" is not installed. This driver can be downloaded from here

    
answered by 02.04.2016 в 22:58