你的位置:首页 > ASP.net教程

[ASP.net教程]mvc项目架构分享系列之架构搭建之Infrastructure


项目架构搭建之Infrastructure的搭建

6.项目架构搭建之Core搭建

    添加对用到的类库的引用,这里用到的包括:.NET自带的两个类库System.Configuration 、 System.Web ,和两个第三方类库 log4net(日志框架) 和 Newtonsoft.Json (Json.Net)

 

  • ConfigurationHelper 【配置文件帮助类】

   

 1   /// <summary> 2  3    /// 网站根路径 4  5    /// </summary> 6  7    private static string siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/"); 8  9  10  11    /// <summary> 12  13    /// 获取配置文件中AppSetting节点的相对路径对应的绝对路径 14  15    /// </summary> 16  17    /// <param name="key">相对路径设置的键值</param> 18  19    /// <returns>绝对路径</returns> 20  21    public static string AppSettingMapPath(string key) 22  23     { 24  25      if (String.IsNullOrEmpty(siteroot)) 26  27       { 28  29        siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/"); 30  31       } 32  33      //拼接路径 34  35      string path = siteroot + System.Configuration.ConfigurationManager.AppSettings[key].ToString(); 36  37      return path; 38  39     } 40  41  42  43    /// <summary> 44  45    /// 将虚拟路径转换为物理路径 46  47    /// </summary> 48  49    /// <param name="virtualPath">虚拟路径</param> 50  51    /// <returns>虚拟路径对应的物理路径</returns> 52  53    public static string MapPath(string virtualPath) 54  55     { 56  57      if (String.IsNullOrEmpty(siteroot)) 58  59       { 60  61        siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/"); 62  63       } 64  65      //拼接路径 66  67      string path = siteroot + virtualPath; 68  69      return path; 70  71     } 72  73  74  75    /// <summary> 76  77    /// 获取配置文件中AppSetting节点的值 78  79    /// </summary> 80  81    /// <param name="key">设置的键值</param> 82  83    /// <returns>键值对应的值</returns> 84  85    public static string AppSetting(string key) => System.Configuration.ConfigurationManager.AppSettings[key].ToString(); 86  87  88  89    /// <summary> 90  91    /// 获取配置文件中ConnectionStrings节点的值 92  93    /// </summary> 94  95    /// <param name="key">键值</param> 96  97    /// <returns>键值对应的连接字符串值</returns> 98  99    public static string ConnectionString(string key) => System.Configuration.ConfigurationManager.ConnectionStrings[key].ConnectionString;100 101 102 103    public static bool UpdateAppSettings(string key, string value)104 105     {106 107      string filename = System.Web.Hosting.HostingEnvironment.MapPath("~/web.config");108 109      new 110 111      try112 113       {114 115         116 117       }118 119      catch (Exception)120 121       {122 123        return false;124 125       }126 127      //文档节点名称数组128 129      foreach (in DocdNodeNameArr)130 131       {132 133        if (element.Name == "appSettings")//找到名称为 appSettings 的节点134 135         {136 137          //子节点名称数组138 139          if (KeyNameArr.Count > 0)140 141           {142 143            foreach (in KeyNameArr)144 145             {146 147              //找到键值,修改为想要修改的值148 149              if ("key"].Inner150 151               {152 153                "value"].Value = value;154 155                ConfigurationManager.RefreshSection("appSettings");156 157                return true;158 159               }160 161             }162 163            //没有相应的节点164 165            return false;166 167           }168 169          else170 171           {172 173            //不存在 AppSettings 节点174 175            return false;176 177           }178 179         }180 181       }182 183      return false;184 185     }186 187 

 

  • PathHelper 【路径帮助类】

    通过 System.Web.Hosting.HostingEnvironment.MapPath() 方法将虚拟路径转换为物理路径

 

1 /// <summary>2 /// 将虚拟路径转换为物理路径3 /// </summary>4 /// <param name="virtualPath">虚拟路径</param>5 /// <returns>虚拟路径对应的物理路径</returns>6 public static string MapPath(string virtualPath) => System.Web.Hosting.HostingEnvironment.MapPath("~/") + virtualPath;

 

  • LogHelper    【日志帮助类】

    根据log4net中的ILog接口中的方法进行封装,在构造函数中设置logger,在程序启动时需要进行log4net的初始化,只初始化一次就可以了所以需要设置为static 静态方法

 

/// <summary>  /// 日志助手  /// </summary>  public class LogHelper  {    private readonly ILog logger = null;    public LogHelper(Type t)    {      logger = LogManager.GetLogger(t);    }    public LogHelper(string name)    {      logger = LogManager.GetLogger(name);    }    public static void LogInit()    {      log4net.Config.public void Debug(string msg)    {      logger.Debug(msg);    }    public void Debug(string msg, Exception ex)    {      logger.Debug(msg, ex);    }    public void Error(string msg)    {      logger.Error(msg);    }    public void Error(string msg, Exception ex)    {      logger.Error(msg, ex);    }    public void Warn(string msg)    {      logger.Warn(msg);    }    public void Warn(string msg, Exception ex)    {      logger.Warn(msg, ex);    }    public void Debug(Exception ex)    {      logger.Debug(ex.Message, ex);    }    public void Error(Exception ex)    {      logger.Error(ex.Message, ex);    }  }

 

  • WebHelper 【Web帮助类】

    包括Web编码解码:html编码解码、url编码解码,Cookies管理,获取客户端信息(IP,浏览器类型、操作系统等信息)

     

     1 #region 编码 2  3     /// <summary> 4     /// HTML解码 5     /// </summary> 6     /// <returns></returns> 7     public static string HtmlDecode(string s) 8     { 9       return HttpUtility.HtmlDecode(s);10     }11 12     /// <summary>13     /// HTML编码14     /// </summary>15     /// <returns></returns>16     public static string HtmlEncode(string s)17     {18       return HttpUtility.HtmlEncode(s);19     }20 21     /// <summary>22     /// URL解码23     /// </summary>24     /// <returns></returns>25     public static string UrlDecode(string s)26     {27       return HttpUtility.UrlDecode(s);28     }29 30     /// <summary>31     /// URL编码32     /// </summary>33     /// <returns></returns>34     public static string UrlEncode(string s)35     {36       return HttpUtility.UrlEncode(s);37     }38 39     #endregion 编码

     1 #region Cookie 2  3     /// <summary> 4     /// 删除指定名称的Cookie 5     /// </summary> 6     /// <param name="name">Cookie名称</param> 7     public static void DeleteCookie(string name) 8     { 9       HttpCookie cookie = new HttpCookie(name); 10       cookie.Expires = DateTime.Now.AddYears(-1); 11       HttpContext.Current.Response.AppendCookie(cookie); 12     } 13  14     /// <summary> 15     /// 获得指定名称的Cookie值 16     /// </summary> 17     /// <param name="name">Cookie名称</param> 18     /// <returns></returns> 19     public static string GetCookie(string name) 20     { 21       HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; 22       if (cookie != null) 23         return cookie.Value; 24  25       return string.Empty; 26     } 27  28     /// <summary> 29     /// 获得指定名称的Cookie中特定键的值 30     /// </summary> 31     /// <param name="name">Cookie名称</param> 32     /// <param name="key">键</param> 33     /// <returns></returns> 34     public static string GetCookie(string name, string key) 35     { 36       HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; 37       if (cookie != null && cookie.HasKeys) 38       { 39         string v = cookie[key]; 40         if (v != null) 41           return v; 42       } 43  44       return string.Empty; 45     } 46  47     /// <summary> 48     /// 设置指定名称的Cookie的值 49     /// </summary> 50     /// <param name="name">Cookie名称</param> 51     /// <param name="value">值</param> 52     public static void SetCookie(string name, string value) 53     { 54       HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; 55       if (cookie != null) 56         cookie.Value = value; 57       else 58         cookie = new HttpCookie(name, value); 59  60       HttpContext.Current.Response.AppendCookie(cookie); 61     } 62  63     /// <summary> 64     /// 设置指定名称的Cookie的值 65     /// </summary> 66     /// <param name="name">Cookie名称</param> 67     /// <param name="value">值</param> 68     /// <param name="expires">过期时间</param> 69     public static void SetCookie(string name, string value, double expires) 70     { 71       HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; 72       if (cookie == null) 73         cookie = new HttpCookie(name); 74  75       cookie.Value = value; 76       cookie.Expires = DateTime.Now.AddMinutes(expires); 77       HttpContext.Current.Response.AppendCookie(cookie); 78     } 79  80     /// <summary> 81     /// 设置指定名称的Cookie特定键的值 82     /// </summary> 83     /// <param name="name">Cookie名称</param> 84     /// <param name="key">键</param> 85     /// <param name="value">值</param> 86     public static void SetCookie(string name, string key, string value) 87     { 88       HttpCookie cookie = HttpContext.Current.Request.Cookies[name]; 89       if (cookie == null) 90         cookie = new HttpCookie(name); 91  92       cookie[key] = value; 93       HttpContext.Current.Response.AppendCookie(cookie); 94     } 95  96     /// <summary> 97     /// 设置指定名称的Cookie特定键的值 98     /// </summary> 99     /// <param name="name">Cookie名称</param>100     /// <param name="key">键</param>101     /// <param name="value">值</param>102     /// <param name="expires">过期时间</param>103     public static void SetCookie(string name, string key, string value, double expires)104     {105       HttpCookie cookie = HttpContext.Current.Request.Cookies[name];106       if (cookie == null)107         cookie = new HttpCookie(name);108 109       cookie[key] = value;110       cookie.Expires = DateTime.Now.AddMinutes(expires);111       HttpContext.Current.Response.AppendCookie(cookie);112     }113 114     #endregion Cookie

     1     //浏览器列表 2     private static string[] _browserlist = new string[] { "ie", "chrome", "mozilla", "netscape", "firefox", "opera", "konqueror" }; 3  4 #region 客户端信息 5  6     /// <summary> 7     /// 是否是get请求 8     /// </summary> 9     /// <returns></returns> 10     public static bool IsGet() 11     { 12       return HttpContext.Current.Request.HttpMethod == "GET"; 13     } 14  15     /// <summary> 16     /// 是否是post请求 17     /// </summary> 18     /// <returns></returns> 19     public static bool IsPost() 20     { 21       return HttpContext.Current.Request.HttpMethod == "POST"; 22     } 23  24     /// <summary> 25     /// 是否是Ajax请求 26     /// </summary> 27     /// <returns></returns> 28     public static bool IsAjax() 29     { 30       return HttpContext.Current.Request.Headers["X-Requested-With"] == ""; 31     } 32  33     /// <summary> 34     /// 获得查询字符串中的值 35     /// </summary> 36     /// <param name="key">键</param> 37     /// <param name="defaultValue">默认值</param> 38     /// <returns></returns> 39     public static string GetQueryString(string key, string defaultValue) 40     { 41       string value = HttpContext.Current.Request.QueryString[key]; 42       if (!string.IsNullOrWhiteSpace(value)) 43         return value; 44       else 45         return defaultValue; 46     } 47  48     /// <summary> 49     /// 获得查询字符串中的值 50     /// </summary> 51     /// <param name="key">键</param> 52     /// <returns></returns> 53     public static string GetQueryString(string key) 54     { 55       return GetQueryString(key, ""); 56     } 57  58     /// <summary> 59     /// 获得查询字符串中的值 60     /// </summary> 61     /// <param name="key">键</param> 62     /// <param name="defaultValue">默认值</param> 63     /// <returns></returns> 64     public static int GetQueryInt(string key, int defaultValue) 65     { 66       return ConverterHelper.StringToInt(HttpContext.Current.Request.QueryString[key], defaultValue); 67     } 68  69     /// <summary> 70     /// 获得查询字符串中的值 71     /// </summary> 72     /// <param name="key">键</param> 73     /// <returns></returns> 74     public static int GetQueryInt(string key) 75     { 76       return GetQueryInt(key, 0); 77     } 78  79     /// <summary> 80     /// 获得表单中的值 81     /// </summary> 82     /// <param name="key">键</param> 83     /// <param name="defaultValue">默认值</param> 84     /// <returns></returns> 85     public static string GetFormString(string key, string defaultValue) 86     { 87       string value = HttpContext.Current.Request.Form[key]; 88       if (!string.IsNullOrWhiteSpace(value)) 89         return value; 90       else 91         return defaultValue; 92     } 93  94     /// <summary> 95     /// 获得表单中的值 96     /// </summary> 97     /// <param name="key">键</param> 98     /// <returns></returns> 99     public static string GetFormString(string key)100     {101       return GetFormString(key, "");102     }103 104     /// <summary>105     /// 获得表单中的值106     /// </summary>107     /// <param name="key">键</param>108     /// <param name="defaultValue">默认值</param>109     /// <returns></returns>110     public static int GetFormInt(string key, int defaultValue)111     {112       return ConverterHelper.StringToInt(HttpContext.Current.Request.Form[key], defaultValue);113     }114 115     /// <summary>116     /// 获得表单中的值117     /// </summary>118     /// <param name="key">键</param>119     /// <returns></returns>120     public static int GetFormInt(string key)121     {122       return GetFormInt(key, 0);123     }124 125     /// <summary>126     /// 获得请求中的值127     /// </summary>128     /// <param name="key">键</param>129     /// <param name="defaultValue">默认值</param>130     /// <returns></returns>131     public static string GetRequestString(string key, string defaultValue)132     {133       if (HttpContext.Current.Request.Form[key] != null)134         return GetFormString(key, defaultValue);135       else136         return GetQueryString(key, defaultValue);137     }138 139     /// <summary>140     /// 获得请求中的值141     /// </summary>142     /// <param name="key">键</param>143     /// <returns></returns>144     public static string GetRequestString(string key)145     {146       if (HttpContext.Current.Request.Form[key] != null)147         return GetFormString(key);148       else149         return GetQueryString(key);150     }151 152     /// <summary>153     /// 获得请求中的值154     /// </summary>155     /// <param name="key">键</param>156     /// <param name="defaultValue">默认值</param>157     /// <returns></returns>158     public static int GetRequestInt(string key, int defaultValue)159     {160       if (HttpContext.Current.Request.Form[key] != null)161         return GetFormInt(key, defaultValue);162       else163         return GetQueryInt(key, defaultValue);164     }165 166     /// <summary>167     /// 获得请求中的值168     /// </summary>169     /// <param name="key">键</param>170     /// <returns></returns>171     public static int GetRequestInt(string key)172     {173       if (HttpContext.Current.Request.Form[key] != null)174         return GetFormInt(key);175       else176         return GetQueryInt(key);177     }178 179     /// <summary>180     /// 获得上次请求的url181     /// </summary>182     /// <returns></returns>183     public static string GetUrlReferrer()184     {185       Uri uri = HttpContext.Current.Request.UrlReferrer;186       if (uri == null)187       {188         return string.Empty;189       }190       return uri.ToString();191     }192 193     /// <summary>194     /// 获得请求的主机部分195     /// </summary>196     /// <returns></returns>197     public static string GetHost()198     {199       return HttpContext.Current.Request.Url.Host;200     }201 202     /// <summary>203     /// 获得请求的url204     /// </summary>205     /// <returns></returns>206     public static string GetUrl()207     {208       return HttpContext.Current.Request.Url.ToString();209     }210 211     /// <summary>212     /// 获得请求的原始url213     /// </summary>214     /// <returns></returns>215     public static string GetRawUrl()216     {217       return HttpContext.Current.Request.RawUrl;218     }219 220     /// <summary>221     /// 获得请求的ip222     /// </summary>223     /// <returns></returns>224     public static string GetIP()225     {226       string ip = string.Empty;227       if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)228         ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();229       else230         ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();231 232       if (string.IsNullOrEmpty(ip) || !ValidateHelper.IsIP(ip))233         ip = "127.0.0.1";234       return ip;235     }236 237     /// <summary>238     /// 获得请求的浏览器类型239     /// </summary>240     /// <returns></returns>241     public static string GetBrowserType()242     {243       string type = HttpContext.Current.Request.Browser.Type;244       if (string.IsNullOrEmpty(type) || type == "unknown")245         return "未知";246 247       return type.ToLower();248     }249 250     /// <summary>251     /// 获得请求的浏览器名称252     /// </summary>253     /// <returns></returns>254     public static string GetBrowserName()255     {256       string name = HttpContext.Current.Request.Browser.Browser;257       if (string.IsNullOrEmpty(name) || name == "unknown")258         return "未知";259 260       return name.ToLower();261     }262 263     /// <summary>264     /// 获得请求的浏览器版本265     /// </summary>266     /// <returns></returns>267     public static string GetBrowserVersion()268     {269       string version = HttpContext.Current.Request.Browser.Version;270       if (string.IsNullOrEmpty(version) || version == "unknown")271         return "未知";272 273       return version;274     }275 276     /// <summary>277     /// 获得请求客户端的操作系统类型278     /// </summary>279     /// <returns></returns>280     public static string GetOSType()281     {282       string userAgent = HttpContext.Current.Request.UserAgent;283       if (userAgent == null)284         return "未知";285 286       string type = null;287       if (userAgent.Contains("NT 6.1"))288         type = "Windows 7";289       else if (userAgent.Contains("NT 5.1"))290         type = "Windows XP";291       else if (userAgent.Contains("NT 6.2"))292         type = "Windows 8";293       else if (userAgent.Contains("android"))294         type = "Android";295       else if (userAgent.Contains("iphone"))296         type = "IPhone";297       else if (userAgent.Contains("Mac"))298         type = "Mac";299       else if (userAgent.Contains("NT 6.0"))300         type = "Windows Vista";301       else if (userAgent.Contains("NT 5.2"))302         type = "Windows 2003";303       else if (userAgent.Contains("NT 5.0"))304         type = "Windows 2000";305       else if (userAgent.Contains("98"))306         type = "Windows 98";307       else if (userAgent.Contains("95"))308         type = "Windows 95";309       else if (userAgent.Contains("Me"))310         type = "Windows Me";311       else if (userAgent.Contains("NT 4"))312         type = "Windows NT4";313       else if (userAgent.Contains("Unix"))314         type = "UNIX";315       else if (userAgent.Contains("Linux"))316         type = "Linux";317       else if (userAgent.Contains("SunOS"))318         type = "SunOS";319       else320         type = "未知";321 322       return type;323     }324 325     /// <summary>326     /// 获得请求客户端的操作系统名称327     /// </summary>328     /// <returns></returns>329     public static string GetOSName()330     {331       string name = HttpContext.Current.Request.Browser.Platform;332       if (string.IsNullOrEmpty(name))333         return "未知";334 335       return name;336     }337 338     /// <summary>339     /// 判断是否是浏览器请求340     /// </summary>341     /// <returns></returns>342     public static bool IsBrowser()343     {344       string name = GetBrowserName();345       foreach (string item in _browserlist)346       {347         if (name.Contains(item))348           return true;349       }350       return false;351     }352 353     /// <summary>354     /// 是否是移动设备请求355     /// </summary>356     /// <returns></returns>357     public static bool IsMobile()358     {359       if (HttpContext.Current.Request.Browser.IsMobileDevice)360         return true;361 362       bool isTablet = false;363       if (bool.TryParse(HttpContext.Current.Request.Browser["IsTablet"], out isTablet) && isTablet)364         return true;365 366       return false;367     }368 369     /// <summary>370     /// 判断是否是搜索引擎爬虫请求371     /// </summary>372     /// <returns></returns>373     public static bool IsCrawler()374     {375       bool result = HttpContext.Current.Request.Browser.Crawler;376       if (!result)377       {378         string referrer = GetUrlReferrer();379         if (referrer.Length > 0)380         {381           foreach (string item in _searchenginelist)382           {383             if (referrer.Contains(item))384               return true;385           }386         }387       }388       return result;389     }390 391     #endregion 客户端信息

     

  • ConverterHelper 【类型转换帮助类】

    Json类型数据的转换是通过开源类库Json.Net来实现,利用反射将DataTable对象转换为List对象,字符串转换为其他常用类型

 

 1 /// <summary> 2   /// 类型转换助手 3   /// </summary> 4   public static class ConverterHelper 5   { 6     /// <summary> 7     /// 利用反射和泛型 8     /// </summary> 9     /// <param name="dt">DataTable 对象</param> 10     /// <returns></returns> 11     public static List<T> DataTableToList<T>(DataTable dt) where T : class, new() 12     { 13       // 定义集合 14       List<T> ts = new List<T>(); 15  16       // 获得此模型的类型 17       Type type = typeof(T); 18       //定义一个临时变量 19       string tempName = string.Empty; 20       //遍历DataTable中所有的数据行 21       foreach (DataRow dr in dt.Rows) 22       { 23         T t = new T(); 24         // 获得此模型的公共属性 25         PropertyInfo[] propertys = t.GetType().GetProperties(); 26         //遍历该对象的所有属性 27         foreach (PropertyInfo pi in propertys) 28         { 29           tempName = pi.Name;//将属性名称赋值给临时变量 30                    //检查DataTable是否包含此列(列名==对象的属性名) 31           if (dt.Columns.Contains(tempName)) 32           { 33             //取值 34             object value = dr[tempName]; 35             //如果非空,则赋给对象的属性 36             if (value != DBNull.Value) 37               pi.SetValue(t, value, null); 38           } 39         } 40         //对象添加到泛型集合中 41         ts.Add(t); 42       } 43  44       return ts; 45     } 46  47     /// <summary> 48     /// 将object对象转换为Json数据 49     /// </summary> 50     /// <param name="obj">object对象</param> 51     /// <returns>转换后的json字符串</returns> 52     public static string ObjectToJson(object obj) 53     { 54       return JsonConvert.SerializeObject(obj); 55     } 56  57     /// <summary> 58     /// 将Json对象转换为T对象 59     /// </summary> 60     /// <typeparam name="T">对象的类型</typeparam> 61     /// <param name="jsonString">json对象字符串</param> 62     /// <returns>由字符串转换得到的T对象</returns> 63     public static T JsonToObject<T>(string jsonString) 64     { 65       return JsonConvert.DeserializeObject<T>(jsonString); 66     } 67  68     /// <summary> 69     /// 从字符串中获取数据 70     /// </summary> 71     /// <param name="content">源字符串</param> 72     /// <returns>字符串中的值</returns> 73     public static string GetContent(string content) 74     { 75       return (String.IsNullOrEmpty(content) ? null : content); 76     } 77  78     /// <summary> 79     /// 将int转换为bool类型 80     /// </summary> 81     /// <param name="value"></param> 82     /// <returns></returns> 83     public static bool ConvertIntToBool(int value) 84     { 85       return (value > 0 ? true : false); 86     } 87  88     #region 转Int 89  90     /// <summary> 91     /// 将string类型转换成int类型 92     /// </summary> 93     /// <param name="s">目标字符串</param> 94     /// <param name="defaultValue">默认值</param> 95     /// <returns></returns> 96     public static int StringToInt(string s, int defaultValue) 97     { 98       if (!string.IsNullOrWhiteSpace(s)) 99       {100         int result;101         if (int.TryParse(s, out result))102           return result;103       }104 105       return defaultValue;106     }107 108     /// <summary>109     /// 将string类型转换成int类型110     /// </summary>111     /// <param name="s">目标字符串</param>112     /// <returns></returns>113     public static int StringToInt(string s)114     {115       return StringToInt(s, 0);116     }117 118     /// <summary>119     /// 将object类型转换成int类型120     /// </summary>121     /// <param name="s">目标对象</param>122     /// <param name="defaultValue">默认值</param>123     /// <returns></returns>124     public static int ObjectToInt(object o, int defaultValue)125     {126       if (o != null)127         return StringToInt(o.ToString(), defaultValue);128 129       return defaultValue;130     }131 132     /// <summary>133     /// 将object类型转换成int类型134     /// </summary>135     /// <param name="s">目标对象</param>136     /// <returns></returns>137     public static int ObjectToInt(object o)138     {139       return ObjectToInt(o, 0);140     }141 142     #endregion 转Int143 144     #region 转Bool145 146     /// <summary>147     /// 将string类型转换成bool类型148     /// </summary>149     /// <param name="s">目标字符串</param>150     /// <param name="defaultValue">默认值</param>151     /// <returns></returns>152     public static bool StringToBool(string s, bool defaultValue)153     {154       if (s.ToLower().Equals("false"))155         return false;156       else if (s.ToLower().Equals("true"))157         return true;158 159       return defaultValue;160     }161 162     /// <summary>163     /// 将string类型转换成bool类型164     /// </summary>165     /// <param name="s">目标字符串</param>166     /// <returns></returns>167     public static bool ToBool(string s)168     {169       return StringToBool(s, false);170     }171 172     /// <summary>173     /// 将object类型转换成bool类型174     /// </summary>175     /// <param name="s">目标对象</param>176     /// <param name="defaultValue">默认值</param>177     /// <returns></returns>178     public static bool ObjectToBool(object o, bool defaultValue)179     {180       if (o != null)181         return StringToBool(o.ToString(), defaultValue);182 183       return defaultValue;184     }185 186     /// <summary>187     /// 将object类型转换成bool类型188     /// </summary>189     /// <param name="s">目标对象</param>190     /// <returns></returns>191     public static bool ObjectToBool(object o)192     {193       return ObjectToBool(o, false);194     }195 196     #endregion 转Bool197 198     #region 转DateTime199 200     /// <summary>201     /// 将string类型转换成datetime类型202     /// </summary>203     /// <param name="s">目标字符串</param>204     /// <param name="defaultValue">默认值</param>205     /// <returns></returns>206     public static DateTime StringToDateTime(string s, DateTime defaultValue)207     {208       if (!string.IsNullOrWhiteSpace(s))209       {210         DateTime result;211         if (DateTime.TryParse(s, out result))212           return result;213       }214       return defaultValue;215     }216 217     /// <summary>218     /// 将string类型转换成datetime类型219     /// </summary>220     /// <param name="s">目标字符串</param>221     /// <returns></returns>222     public static DateTime StringToDateTime(string s)223     {224       return StringToDateTime(s, DateTime.Now);225     }226 227     /// <summary>228     /// 将object类型转换成datetime类型229     /// </summary>230     /// <param name="s">目标对象</param>231     /// <param name="defaultValue">默认值</param>232     /// <returns></returns>233     public static DateTime ObjectToDateTime(object o, DateTime defaultValue)234     {235       if (o != null)236         return StringToDateTime(o.ToString(), defaultValue);237 238       return defaultValue;239     }240 241     /// <summary>242     /// 将object类型转换成datetime类型243     /// </summary>244     /// <param name="s">目标对象</param>245     /// <returns></returns>246     public static DateTime ObjectToDateTime(object o)247     {248       return ObjectToDateTime(o, DateTime.Now);249     }250 251     #endregion 转DateTime252 253     #region 转Decimal254 255     /// <summary>256     /// 将string类型转换成decimal类型257     /// </summary>258     /// <param name="s">目标字符串</param>259     /// <param name="defaultValue">默认值</param>260     /// <returns></returns>261     public static decimal StringToDecimal(string s, decimal defaultValue)262     {263       if (!string.IsNullOrWhiteSpace(s))264       {265         decimal result;266         if (decimal.TryParse(s, out result))267           return result;268       }269 270       return defaultValue;271     }272 273     /// <summary>274     /// 将string类型转换成decimal类型275     /// </summary>276     /// <param name="s">目标字符串</param>277     /// <returns></returns>278     public static decimal StringToDecimal(string s)279     {280       return StringToDecimal(s, 0m);281     }282 283     /// <summary>284     /// 将object类型转换成decimal类型285     /// </summary>286     /// <param name="s">目标对象</param>287     /// <param name="defaultValue">默认值</param>288     /// <returns></returns>289     public static decimal ObjectToDecimal(object o, decimal defaultValue)290     {291       if (o != null)292         return StringToDecimal(o.ToString(), defaultValue);293 294       return defaultValue;295     }296 297     /// <summary>298     /// 将object类型转换成decimal类型299     /// </summary>300     /// <param name="s">目标对象</param>301     /// <returns></returns>302     public static decimal ObjectToDecimal(object o)303     {304       return ObjectToDecimal(o, 0m);305     }306 307     #endregion 转Decimal308   }

 

7.项目架构搭建之Models搭建

    参考 这里 了解 EF CodeFirst,首先对EF类库进行引用,由于我的应用的使用的是SQLServer数据库,所以需要对EntityFramework.SqlServer进行引用,如果不引用子在进行数据库相关操作时会出错,错误如下:

The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

 

  1. 添加类库引用
  2. 创建Entity

    创建一个类,继承DbContext类,并在他的构造函数中设置连接字符串或者构造函数中传递配置文件中ConnectionStrings的name

  3. 创建数据模型models

    创建Web应用中用到的Model对应数据库中的表,ViewModel另外设置,这里的models对应数据库的数据表,User示例:

  4. 启用数据迁移 EnableMigration
    1. 打开 Package Manager Console
    2. 执行命令 "Enable-Migrations",如果这个项目中有两个或两个以上的继承DbContext类的Entity,需要制定Context的名称,不然会提示有多个Context。
    3. 执行命令之后会生成一个 Migrations文件夹,文件夹下有一个Configuration文件,打开文件修改构造函数,设置 AutomaticMigrationsEnabled = true;