How to make database connectivity in ASP.NET core with PostgreSQL? - sql

How to make database connection in ASP.NET core with postgres SQL ?

Question: How to make database connection in ASP.NET core with postgres SQL ?
There are two ways you add your postgresql database along with the asp.net core project.
Using follwing way:
ADO.net connection provider
Nuget extension: Npgsql.EntityFrameworkCore.PostgreSQL
ADO.net connection provider
Here would just need the NpgsqlConnection connection builder class which will execute your sql on Postgre sql database server. See the example below:
C# ASP.NET Core & Postgre SQL Ado.net example:
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;Password=pwd;Database=postgres;");
conn.Open();
// Passing PostGre SQL Function Name
NpgsqlCommand command = new NpgsqlCommand("EXE GetEmployeePrintInfo", conn);
// Execute the query and obtain a result set
NpgsqlDataReader reader = command.ExecuteReader();
// Reading from the database rows
List<string> listOfManager = new List<string>();
while (reader.Read())
{
string WSManager = reader["WSManager"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
listOfManager.Add(WSManager);
}
reader.Close();
command.Dispose();
conn.Close();
Npgsql.EntityFrameworkCore.PostgreSQL:
You have to add Nuget extension into the project reference from manage Nuget Packages using Visual studio. Entity framework core has this functionality for many database providers. Just follow below steps on visual studio
ConfigureServices in startup.cs:
Once you successfully added the Nuget package then you have to update following code on your project ConfigureServices under startup.cs
services.AddDbContext<YourDatabaseContextClassName>(options =>
options.UseNpgsql(Configuration.GetConnectionString("YourDatabaseContextStringNameFromAppsettings")));
Note: If you need any example for entityframework and Postgre SQL implementation you can have look here
For further assistance you can have look on official document here. Hope it would guide you accordingly.

Related

DiffGrams for .NET Core. We are upgrading our project to .NET Core 3.x so need to find the DiffGrams used in the previous version of .NET

We are upgrading our .NET 2.0 application to .NET Core 3.x there's a DiffGrams used to capture the Table field updates (before/after values) used for Auditing purpose. I have to achieve the similar in the .NET Core 3.x. I am not sure which one is the equivalent for .NET Core 3.x.
Could you anyone help me guide on this? Thank you.
DataSet.WriteXml/DataSet.ReadXml method applies to .NET Core 3.x.
The WriteXml method provides a way to write either data only, or both data and schema from a DataSet into an XML document.
private void WriteXmlToFile(DataSet thisDataSet)
{
if (thisDataSet == null) { return; }
// Create a file name to write to.
string filename = "XmlDoc.xml";
// Create the FileStream to write with.
System.IO.FileStream stream = new System.IO.FileStream
(filename, System.IO.FileMode.Create);
// Create an XmlTextWriter with the fileStream.
System.Xml.XmlTextWriter xmlWriter =
new System.Xml.XmlTextWriter(stream,
System.Text.Encoding.Unicode);
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(xmlWriter, XmlWriteMode.DiffGram);
xmlWriter.Close();
}
The resultant XML code is rooted in the <diffgr:diffgram> node and contains up to three distinct data sections, as follows:
<diffgr:diffgram>
<MyDataSet>
:
</MyDataSet>
<diffgr:before>
:
</diffgr:before>
<diffgr:errors>
:
</diffgr:errors>
</diffgr:diffgram>

ODP.NET Core - Scaffold DB-Context

I am working with oracles odp.net core beta 3. Specifically, The dll is Oracle.ManagedDataAccess.Core.2.12.0-beta3. The project is to create a web api that sits on top of an oracle instance.
My question - Is the command "Scaffold-DBContext" supported with this provider. If so what am I doing wrong... I've made the attempt using a connection string similar to the following.
Data Source={databasename}/{TNS}.domain.local; User ID={UserName};Password={Password};
And the actual command in the Package Manager terminal
Scaffold-DbContext Data Source={databasename}/{TNS}.domain.local; User ID={UserName};Password={Password};" Oracle.ManagedDataAccess -OutputDir Models -Tables {TableName}
I get the following error which sugests it cannot fond a DesignTimeServiceAttribute in the provider assembly.
I also have Microsoft.EntityFrameworkCore.Tools (2.2.0) referenced which includes the design tools.
ERROR
System.InvalidOperationException: Unable to find expected assembly attribute named DesignTimeProviderServicesAttribute in provider assembly Oracle.ManagedDataAccess. This attribute is required to identify the class which acts as the design-time service provider factory.
at Microsoft.EntityFrameworkCore.Design.Internal.DesignTimeServicesBuilder.ConfigureProviderServices(String provider, IServiceCollection services, Boolean throwOnError)
at Microsoft.EntityFrameworkCore.Design.Internal.DesignTimeServicesBuilder.Build(String provider)
at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
I experienced the problems that you experienced, even after downloading the ODP.NET Core driver for production (2.18.3, released on 20-Sept-2018 and available from nuget at https://www.nuget.org/packages/Oracle.ManagedDataAccess.Core/).
I contacted the Oracle community for help. A kind soul answered that there's another piece of the puzzle if we want to have a ready access to goodness such as "UseOracle." It is the Oracle provider for the Entity Framework Core. See the thread at https://community.oracle.com/thread/4180739.
The only other way to use it, to my knowledge and based on his answer, is the way described in the Oracle Help Center, Getting Started with ODP.NET Core (https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/ODPNET_Core_get_started/index.html).
I managed to scaffold it using
scaffold-dbcontext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=1.1.1.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=MYdb)));Persist Security Info=True;User Id=MYUSER;Password=mypass;" Oracle.EntityFrameworkCore
But it's an unusable mess. tons of errors
Could not scaffold the foreign key 'XX.TABLE1(USER_ID,USER_ID)'. A key for 'ID,ID' was not found in the principal entity type 'Aspnetusers'.
Seems like Dapper is my friend...
I scaffolded some tables using this:
Scaffold-DbContext "Data Source=myDatabase.example.com/servicename;
User ID=username;Password=password;" Oracle.EntityFrameworkCore
-OutputDir myModels -Tables FIRSTTABALE,SECONDTABLE
The table names must be in uppercase and Oracle EntityFrameworkCore version was 2.19.30.
The produced models were totally fine. Maybe it depends on the EF Core version or on specifying the table names.
For oracle db use this into View->Other Windows->Package Manager Console:
Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT={your port}))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={db SID})));User ID={username};Password={pass};Persist Security Info=True" Oracle.EntityFrameworkCore -Tables TABLE1, TABLE2, ..., TABLEK -OutputDir Models -force

Serilog MSSqlServer sink not writing to table

I have the following statement in my Startup.cs:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.ColoredConsole()
.WriteTo.MSSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=myDb.Logging;Trusted_Connection=True;", "Logs", autoCreateSqlTable: true)
.WriteTo.RollingFile(pathFormat: Path.Combine(logPath, "Log-{Date}.txt"))
.CreateLogger();
And in my Configure method:
loggerFactory.AddSerilog();
When I start the application, the table is created so I know the connection works. I get logged output to the console and to the file, however, no output to the database table.
What am I failing to do?
Other information: using asp.net core rc2-final, targeting net461, and using Serilog.Sinks.MSSqlServer 4.0.0-beta-100
At first glance it doesn't look like you're missing anything. It's likely that an exception is being thrown by the SQL Server Sink when trying to write to the table.
Have you tried checking the output from Serilog's self log?
Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));
Update:
Looks like a permission issue with you SQL Server/Local DB. This error message suggests the sink is trying to run an ALTER TABLE statement and the user running the application doesn't have permission to execute an ALTER TABLE statement.
Update 2: I suggest you write a simple Console App using the full .NET + Serilog v1.5.14 + Serilog.Sinks.MSSqlServer v3.0.98 to see if you get the same behavior... Just to rule out the possibility that there's a problem with the .NET Core implementation or with the beta sink version you're using

Microsoft sync framework 2.1 ServerSyncProviderProxy with client SQL Server Express

I've been following the tutorial here to configure a proxy service with WCF for synchronization. But all the examples I see the ClientProvider is for SqlServer Compact Edition. Can it be done with the SqlSyncProvider for SQL Server Express?
For example my code is:
var svc = new ServiceForSyncClient();
ServerSyncProvider serverProvider = new ServerSyncProviderProxy(svc);
// create the sync orhcestrator
var syncOrchestrator = new SyncOrchestrator
{
LocalProvider = new SqlSyncProvider("ProductsScope", clientConn),
RemoteProvider = serverProvider,
Direction = SyncDirectionOrder.DownloadAndUpload
};
var syncStats = syncOrchestrator.Synchronize();
But when synchronizing, I get an exception:
An unhandled exception of type 'System.InvalidCastException' occurred
in Microsoft.Synchronization.dll
Additional information:
Microsoft.Synchronization.KnowledgeSyncProvider
you're using two completely different sync providers. part of your code is using the the older offline providers (DBServerSyncProvider and SQLCEClientSyncProvider) and you're trying to use the SQLSyncProvider which is part of the newer knowledge-based/peer-to-peer sync provider (SqlSycProvider/SqlCeSyncProvider).
You can't mix and match the older and newer sync providers
If you want to use SQL Express as the client, here is a sample for using it with WCF

Failure to create a SQL Azure login with SMO

The following piece of code works with regular SQL and SMO. I'm trying to get it to work with SQL Azure. According to this MSDN article, a limited subset of functionality that I need (database and login creation) should be supported. All the business checking whether an object exists will also fail: server.Logins[loginName] != null or server.Databases.Contains(dbName). I can create a database if I dont check whether it exists or not, but i cant create a login. Anyone else ran into the same problem?
string connectionString =
"Server=tcp:XXXXXX.database.windows.net;Database=MyDatabase;User ID=XXXXXXX;Password=XXXXXX;Trusted_Connection=False;Encrypt=True;TrustServerCertificate=true;"
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
ServerConnection serverConnection = new ServerConnection(connection);
Server server = new Server(serverConnection);
Login login = new Login(server, "NewLogin");
login.LoginType = LoginType.SqlLogin;
login.Create("NewStrongPwd123***");
}
Create failed for Login 'NewLogin'.
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImpl()
at Microsoft.SqlServer.Management.Smo.Login.Create(SecureString password)
at Microsoft.SqlServer.Management.Smo.Login.Create(String password)
Proposed answers to this question were identified on the MSDN Forum including a working approach. Please take a look at: http://social.msdn.microsoft.com/Forums/en-US/ssdsgetstarted/thread/26e42082-e649-4cde-916d-c1da2275e377