初试 .Net Core 2.0

初识.Net Core2.0

 上周微软一不小心,提前发布了.Net Core 2.0,简单上手,发现比起.Net Core1.1有了很大的改变,支持的API也更多了,使用体验也更好了.简单说说.

新增项目模板

.Net Core 项目模板
项目模板是多了不少

与.Net Core1.1区别

using System;
using System.Data;
using System.Data.SqlClient;

namespace qiufeng.console
{
    class Program
    {
        static void Main(string[] args)
        {
            //1. 在.net core1.1中,如果不指定Console.OutputEncoding为utf-8的话,中文是乱码的
            Console.WriteLine("Hello World!");
            Console.WriteLine("测试中文");
            Console.WriteLine("============================================");

            //2. 测试能否使用sqlserver
            //在.net core1.1 连接sqlserver数据库不能低于 sqlserver 2008 r2 sp3
            //但在.net core2.0中,是可以直接使用sqlserver 2005
            SqlConnection connection = new SqlConnection("Data Source=192.168.68.5;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=123");

            SqlCommand sqlCommandVersion = new SqlCommand("select @@version", connection);
            SqlCommand command = new SqlCommand("select top 10 nid,sname from d_doctorinfo where nid > 8020966", connection);
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }

            string versionInfo = sqlCommandVersion.ExecuteScalar() as string;
            Console.WriteLine($"数据库版本信息:{versionInfo}");
            Console.WriteLine("============================================");

            //读取表中数据,并打印到控制台中
            SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            if (reader.HasRows)
            {
                int i = 0;
                while (reader.Read())
                {
                    int id = reader.GetInt32(0);
                    string name = reader.GetString(1);
                    Console.WriteLine($"index={++i}  id={id}   name={name}");
                }
            }
            else
            {
                Console.WriteLine("没有数据!");
            }
            reader.Close();
            connection.Close();

            Console.ReadKey();
        }
    }
}

使用Nuget,安装System.Data.SqlClient

引用sqlclient.dll

打印效果:

.net core使用sqlserver 2005

上面这两种,在.Net Core1.1的时候使用,让人很不爽,但现在没问题,可以很愉快使用啦.

.Net Core 2.0 发布

支持更多的API,也更模块化了,但发布的独立可执行程序,是越来越大了,1.1的时候,console程序发布之后有四十兆,2.0发布之后有六十多兆,web程序,竟然有九十多兆,所以要了解自己程序的依赖,适当裁剪还是必要的.
秋风 2017-08-22