I need to connect my ASP.net MVC project via ConnectionString to my Google Cloud SQL/PgAdmin 4

0

I am new here and this is my first question. I have some issues with connecting databases in general, I've only ever succeeded with local databases in Visual Studio.

Background

Software used for this project:

  • Visual Studio Enterprise 2019
  • PostgreSQL 12(?)
  • PgAdmin4
  • Google Cloud SQL (PostgreSQL 12).

I am programming in C#. I created a new database in the Google Cloud Platform using the free trial. I have a database up and running called "DrinkandDine" en_US.UTF8 UTF8. The Instance as it says is "jasc1800" which is what I named it.

I created a new connection inside the Google Cloud Platform through Public IP:

Name: DrinkAndDine Network: MY IPv4 address

I then went into PgAdmin 4 and connected to this server database. It works and I have created a table called "users" so far with just an ID and email.

Connection

Inside the Visual Studio ASP.net MVC project I put this into the connectionStrings in the Web.config:

<add name="DefaultConn" connectionString="Server=35.xx.x.xx; Port=5432; Database=DrinkandDine; User Id=postgres; Password=xx;"/>

This I did because I understand that I need to connect to the PgAdmin 4 database? Or have I understood this wrong? The Visual Studio project connects to the PgAdmin 4 connection and then PgAdmin 4 is connected to the Google Cloud Platform.

I wanted to then display all users on a page

I created a class called AppDbContext : DbContext (Inherits from DbContext) and inside I put the following code:

public List<User> GetAllUsers()
        {
            User user;
            List<User> userList = new List<User>();
    
            string stmt = "SELECT * FROM User";
    
            var conn = new 
            NpgsqlConnection(ConfigurationManager.ConnectionStrings["DefaultConn"].ConnectionString);
            conn.Open();
    
            var cmd = new NpgsqlCommand(stmt, conn);
            var reader = cmd.ExecuteReader();
    
            while (reader.Read())
            {
                user = new User()
            {
                Id = reader.GetInt32(0),
                Email = reader.GetString(1),
            };
            }
    return userList;
    }

Then I created the following in the HomeController:

public ActionResult GetAllUsers()
    {
        AppDbContext db = new AppDbContext();
        return View(db.GetAllUsers());
    }

Afterwards I put this into a view which I called GetAllUsers:

@model List<DrinkAndDine.Models.User>
        @{
        ViewBag.Title = "GetAllUsers";
        }
    
        <div>
        <h2>These are the users on the website</h2>
        <p>
            @foreach (var item in Model)
            {
                <p>
                    ID: @item.Id Email: @item.Email
                </p>
            }
        </p>
        </div>

When I launch the page to see the users I get this:

System.InvalidCastException
  HResult=0x80004002
  Message=Can't cast database type name to Int32
  Source=Npgsql
  StackTrace:
   at Npgsql.TypeHandling.NpgsqlTypeHandler`1.Read[TAny](NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
   at Npgsql.TypeHandling.NpgsqlTypeHandler`1.Read[TAny](NpgsqlReadBuffer buf, Int32 len, FieldDescription fieldDescription)
   at Npgsql.NpgsqlDataReader.GetFieldValue[T](Int32 ordinal)
   at Npgsql.NpgsqlDataReader.GetInt32(Int32 ordinal)
   at DrinkAndDine.Models.AppDbContext.GetAllUsers() in C:\Users\jakob\OneDrive\Desktop\Programming\Visual Studio Projects\DrinkAndDine\Models\AppDbContext.cs:line 34
   at DrinkAndDine.Controllers.HomeController.GetAllUsers() in C:\Users\jakob\OneDrive\Desktop\Programming\Visual Studio Projects\DrinkAndDine\Controllers\HomeController.cs:line 34
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()

This is a lot of information, I don't know what I need to do or doing wrong. I tried a different approach in the beginning which didn't work either.

c#
asp.net-mvc
postgresql
visual-studio
pgadmin-4
asked on Stack Overflow Mar 4, 2021 by Graphit

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0