码迷,mamicode.com
首页 > 数据库 > 详细

asp.net core连接sqlserver

时间:2019-02-16 13:49:42      阅读:1097      评论:0      收藏:0      [点我收藏+]

标签:length   datatable   using   close   config   span   client   类库   sys   

开发环境:win7,vs2017,sqlserver2014

vs上建立一个asp.net core web项目和一个.net core的类库项目DBA

简单起见,在DBA项目中就一个类SqlServerManager:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;

namespace DBA
{
    public class SqlServerManager : DbContext
    {
        private IDbConnection connection = null;
        private SqlCommand command = null;
        public SqlServerManager(DbContextOptions<SqlServerManager> options) : base(options) {
            if(null== connection)
                connection = Database.GetDbConnection();//这个GetDbConnection需要在NuGet中添加Microsoft.AspNetCore.App

            if (connection.State == ConnectionState.Closed)
                connection.Open();
            if (command == null)
                command=connection.CreateCommand() as SqlCommand;

        }

        

        public int Insert<T>(T table)
        {
            try { 
            command.CommandText = GetInsertSqlStr(table, command.Parameters);
            return command.ExecuteNonQuery();}
            catch(Exception ex)
            {
                throw ex;
            }
        }
        public void ExecSqlStr(string sql,Dictionary<string,object> Parameters)
        {
            command.CommandText = sql;
            foreach(var str in Parameters.Keys)
            {
                var value = Parameters.GetValueOrDefault(str);
                command.Parameters.Add(
                    new SqlParameter()
                    {
                        ParameterName="@"+str,
                        Value= value,
                        DbType= GetDbType(value.GetType())
                    }
                    );
            }
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = command;
            DataSet myDataSet = new DataSet();
            da.Fill(myDataSet);
            DataTable db = myDataSet.Tables[0];
        }


        private string GetInsertSqlStr<T>(T table,SqlParameterCollection sqlParameters)
        {
            string strSql = "insert into "+ typeof(T).Name + " (";
            //获得泛型类型的公共属性
            var pros = typeof(T).GetProperties().Where(pi => !Attribute.IsDefined(pi, typeof(NotMappedAttribute))).ToArray();
            string values = "";
            foreach (PropertyInfo p in pros)
            {
                strSql += p.Name + ",";
                values += "@" + p.Name + ",";

                sqlParameters.Add(new SqlParameter() {
                    ParameterName = "@" + p.Name,
                    Value = p.GetValue(table),
                    DbType = GetDbType(p.PropertyType)
                });
            }
            values = values.Substring(0, values.Length - 1);
            strSql = strSql.Substring(0, strSql.Length - 1) + ") values ("+ values+")";
            return strSql;
        }

        private DbType GetDbType(Type t)
        {
            switch (Type.GetTypeCode(t))
            {
                case TypeCode.Boolean:
                    return DbType.Boolean;
                case TypeCode.Byte:
                    return DbType.Byte;
                case TypeCode.DateTime:
                    return DbType.DateTime;
                case TypeCode.Decimal:
                    return DbType.Decimal;
                case TypeCode.Double:
                    return DbType.Double;
                case TypeCode.Int16:
                    return DbType.Int16;
                case TypeCode.Int32:
                    return DbType.Int32;
                case TypeCode.Int64:
                    return DbType.Int64;              
                case TypeCode.String:
                    return DbType.String;
                default:
                    return DbType.Object;
            }
        }
    }
}

本文的重点不在于DBA项目中如何去访问数据库,这里可以用EF,也可以用ADO.NET等等,我这里用的是ADO.NET

重点在于如何在web项目中去调用DBA项目来实现数据库的访问

首先肯定是要添加DBA项目的引用。

然后在web项目的Startup类的ConfigureServices函数中添加代码:

技术图片

注意这里的数据库连接字符串,里面没有用户名和密码,就这样就可以了

然后在控制器中通过构造函数来获取SqlServerManager的对象

技术图片

 

 好了,这样就可以访问数据库了,只是一个简单的例子,看看就好

asp.net core连接sqlserver

标签:length   datatable   using   close   config   span   client   类库   sys   

原文地址:https://www.cnblogs.com/jin-/p/10387208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!