System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding

最近搞 .net项目,Dapper连接Mysql时,运行报错:

System.NotSupportedException:“No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.”

 

解决办法:

新建项目,选择Visual C#   ->    .Net Core    ->    控制台应用(.Net Core)

数据库语句:

CREATE TABLE `city` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` char(35) NOT NULL DEFAULT '',
  `CountryCode` char(3) NOT NULL DEFAULT '',
  `District` char(20) NOT NULL DEFAULT '',
  `Population` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  KEY `CountryCode` (`CountryCode`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

测试代码:

 1 using System;
 2 using MySql.Data.MySqlClient;
 3 using Dapper;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 
 7 namespace ConsoleApp1
 8 {
 9 
10     public class CityEntity
11     {
12         public int ID { get; set; }
13         public string Name { get; set; }
14         public string CountryCode { get; set; }
15         public string District { get; set; }
16         public int Population { get; set; }
17 
18         public override string ToString()
19         {
20             return $"ID: {ID}, Name: {Name}, CountryCode: {CountryCode}, District: {District}, Population: {Population}";
21         }
22     }
23     public class CityRepository
24     {
25         public List<CityEntity> Get10Cities()
26         {
27             List<CityEntity> result;
28             using (var conn = new MySqlConnection("Host=172.16.1.197;Port=3306;Database=mars_xusinan;Uid=root;pwd=123456"))
29             {
30                 var sql = "SELECT * FROM city";
31                 result = conn.Query<CityEntity>(sql).ToList();
32             }
33 
34             return result;
35         }
36     }
37     class Program
38     {
39         static void Main(string[] args)
40         {
41             var repository = new CityRepository();
42             var cities = repository.Get10Cities();
43             cities.ForEach(e =>
44             {
45                 System.Console.WriteLine(e);
46             });
47         }
48     }
49 }
View Code

添加引用:用NuGet得到包

Dapper 

MySql.Data

安装完后,报错自然消失,大功告成,搞了2天,坚持不放弃。

posted @ 2019-12-20 14:19  菜鸡徐思  阅读(7131)  评论(0编辑  收藏  举报