Core 3 Core 6 連線到GoDaddy的MySql的問題,

可以做Core MVC 專案,連線GoDaddy,但試過,目前還是只能Core 3.1,如果程式Core 6是在本機,連線GoDaddy的MySql可以讀出資料,但Core 6的程式上傳到GoDaddy就沒辦法,2023-11-08為止還是沒辦法,因為GoDaddy還是用Core 3.1,所以只能用已不支援的Core 3.1來開發,測試是可以讀出MySql,如果是自已架Server,那就都沒問題。

Core 6

在Vs2022 NuGet安裝套件

Install-Package Pomelo.EntityFrameworkCore.MySql

Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.Tools

使用DB First

Scaffold-DbContext "Data Source=GoDaddy連線資料;Port=3306;Database=資料庫名;Uid=帳號;Pwd=密" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -UseDatabaseNames -Force

成功後

Program.cs

var builder = WebApplication.CreateBuilder(args);

//MS SQL用
//builder.Services.AddDbContext<自訂連線名>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("自訂連線名")));

//MySql用
builder.Services.AddDbContext<自訂連線名>(options =>
{
   options.UseMySql(builder.Configuration.GetConnectionString("自訂連線名") ?? throw new InvalidOperationException("Connection string '自訂連線名' not found."),
   ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("自訂連線名")));
   options.EnableSensitiveDataLogging(true);  // 啟用敏感數據日誌
   options.LogTo(Console.WriteLine, LogLevel.Information);  // 將日誌輸出到控制台
});

appsettings.json

{
 "Logging": {
   "LogLevel": {
     "Default": "Information",
     "Microsoft.AspNetCore": "Warning"
   }
 },
 "AllowedHosts": "*",
 "ConnectionStrings": {
   "acprando_dbContext": "Data Source=GoDaddy連線資料;Port=3306;Database=資料庫名;Uid=帳號;Pwd=密碼"
  }
 }

在HomeController.cs測試

       private readonly ILogger<HomeController> _logger;
       private readonly 自訂連線名 _自訂連線名;

       public HomeController(ILogger<HomeController> logger, acprando_dbContext acprado_dbContext)
       {
           _logger = logger;
           _自訂連線名 =自訂連線名;
       }

       //public IActionResult Index()
       //{
       //    return View();
       //}

       public string? Index()
       {
           return _自訂連線名.Table名.FirstOrDefault()?.欄位名稱;

       }

2023-11-08 補充

因為發現GoDaddy目前還是用Core3.1, 所以要用以下套件,將要淘汰的版本,沒辦法,這空間沒更新前,也只能這樣了。我上傳後測試是可以讀出資料庫。

如果在自已VS2022用Core 6 的套件連線到GoDaddy資料庫,是可以讀出資料庫資料,但是程式上傳到GoDaddy文件目錄執行,結果會出現錯誤。

Error.

An error occurred while processing your request.

所以只能用Core 3的語法使用。

在Startup.cs

using 專案名稱.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace 專案名稱
{
    public class Startup
    {
        private readonly IConfiguration Configuration;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }



        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<連線名稱>(optionsBuilder => optionsBuilder.UseMySql(
                Configuration.GetConnectionString("連線名稱"), 
                Microsoft.EntityFrameworkCore.ServerVersion.Parse("5.7.26-mysql")));

            // Add framework services.
            services.AddMvc();
            services.AddScoped<acprando_dbContext>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace 專案名稱
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "連線名稱": "data source=xxxxx.secureserver.net;port=3306;database=db名稱;uid=xxxxx;pwd=xxxxx;ConvertZeroDateTime=True"
  
}

\Model\BlogContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

#nullable disable

namespace Core3M.Models
{
    public partial class BlogContext : DbContext
    {
        public BlogContext()
        {
        }

        public BlogContext(DbContextOptions<BlogContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {            
		//===========用appsettings.json,這連線字串就可以刪除==================
		#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
		//optionsBuilder.UseMySql("server=localhost;port=3306;database=alan;user=root;password=XXXXX", Microsoft.EntityFrameworkCore.ServerVersion.Parse("10.11.1-mariadb"));  //連線自已Mariadb
		//optionsBuilder.UseMySql("server=xxxxx.secureserver.net;port=3306;database=xxx_db;user=xxx;password=xxxxx", Microsoft.EntityFrameworkCore.ServerVersion.Parse("6, 7, 9"));  //連線Godaay方式1 會錯誤
		//optionsBuilder.UseMySql("server=xxxxx.secureserver.net;port=3306;Connect Timeout=5;database=xxxx_db;user=xxxx;password=xxxxx", new MySqlServerVersion(new Version(6, 7, 9)));  //連線Godaay方式2
		optionsBuilder.UseMySql("server=xxxxxx.secureserver.net;port=3306;Connect Timeout=5;database=xxx_db;UserId=xxxxxx;Password=xxxxx", Microsoft.EntityFrameworkCore.ServerVersion.Parse("5.7.26-percona")); //連線Godaay方式3                
		//===========用appsettings.json,這連線字串就可以刪除==================
            }
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasCharSet("utf8mb3")
                .UseCollation("utf8mb3_general_ci");

            modelBuilder.Entity<Student>(entity =>
            {
                entity.ToTable("student");

                entity.HasIndex(e => e.Name, "ix_student_name");

                entity.Property(e => e.Id)
                    .HasColumnType("int(11)")
                    .HasColumnName("id");

                entity.Property(e => e.Age)
                    .HasColumnType("int(11)")
                    .HasColumnName("age");

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasMaxLength(32)
                    .HasColumnName("name")
                    .HasDefaultValueSql("''");

                entity.Property(e => e.Sex)
                    .HasColumnType("tinyint(4)")
                    .HasColumnName("sex")
                    .HasDefaultValueSql("'1'");
            });

            modelBuilder.Entity<acp_detail>(entity =>
            {
                entity.ToTable("acp_detail");
                entity.HasKey(e => e.d_serino).HasName("PRIMARY");

                entity.Property(e => e.cname).HasMaxLength(30);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

//用appsettings.json,這連線字串就可以刪除

 

\Controllers\SampleController.cs

using Core3M.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core3M.Controllers
{
    public class SampleController : Controller
    {
        private readonly BlogContext _db;
        public SampleController(BlogContext dbContext)
        {
            _db = dbContext;
}
        public IActionResult Index()
        {
            var data = _db.Set<Model下的一個Table名稱>().FirstOrDefault();
            ViewData["aa"] = data.cname;

            return View();
        }
    }
}

\Views\Sample\Index.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <div>
        姓名
    </div>
    <div>
        @ViewData["aa"]
    </div>
</body>
</html>