项目架构搭建之Infrastructure的搭建
Contents
系列一【架构概览】
0.项目简介
1.项目解决方案分层方案
2.所用到的技术
3.项目引用关系
系列二【架构搭建初步】
4.项目架构各部分解析
5.项目创建
系列三 【Infrastructure搭建】
6.项目架构搭建之Core搭建
7.项目架构搭建之Models搭建
系列四 【Repository和Service的搭建】
8.项目架构搭建之IDAL搭建
9.项目架构搭建之MSSQLDAL搭建
10.项目架构搭建之IBLL搭建
11.项目架构搭建之BLL搭建
系列五 【UI搭建】
12.WebHelper搭建
13.Web搭建
14.AdminLogic搭建
系列六 【项目扩展】
15.新增Model的处理
6.项目架构搭建之Core搭建
添加对用到的类库的引用,这里用到的包括:.NET自带的两个类库System.Configuration 、 System.Web ,和两个第三方类库 log4net(日志框架) 和 Newtonsoft.Json (Json.Net)
- ConfigurationHelper 【配置文件帮助类】
/// <summary> /// 网站根路径 /// </summary> private static string siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/"); /// <summary> /// 获取配置文件中AppSetting节点的相对路径对应的绝对路径 /// </summary> /// <param name="key">相对路径设置的键值</param> /// <returns>绝对路径</returns> public static string AppSettingMapPath(string key) { if (String.IsNullOrEmpty(siteroot)) { siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/"); } //拼接路径 string path = siteroot + System.Configuration.ConfigurationManager.AppSettings[key].ToString(); return path; } /// <summary> /// 将虚拟路径转换为物理路径 /// </summary> /// <param name="virtualPath">虚拟路径</param> /// <returns>虚拟路径对应的物理路径</returns> public static string MapPath(string virtualPath) { if (String.IsNullOrEmpty(siteroot)) { siteroot = System.Web.Hosting.HostingEnvironment.MapPath("~/"); } //拼接路径 string path = siteroot + virtualPath; return path; } /// <summary> /// 获取配置文件中AppSetting节点的值 /// </summary> /// <param name="key">设置的键值</param> /// <returns>键值对应的值</returns> public static string AppSetting(string key) => System.Configuration.ConfigurationManager.AppSettings[key].ToString(); /// <summary> /// 获取配置文件中ConnectionStrings节点的值 /// </summary> /// <param name="key">键值</param> /// <returns>键值对应的连接字符串值</returns> public static string ConnectionString(string key) => System.Configuration.ConfigurationManager.ConnectionStrings[key].ConnectionString; public static bool UpdateAppSettings(string key, string value) { string filename = System.Web.Hosting.HostingEnvironment.MapPath("~/web.config"); XmlDocument xmldoc = new XmlDocument(); try { xmldoc.Load(filename); } catch (Exception) { return false; } XmlNodeList DocdNodeNameArr = xmldoc.DocumentElement.ChildNodes;//文档节点名称数组 foreach (XmlElement element in DocdNodeNameArr) { if (element.Name == "appSettings")//找到名称为 appSettings 的节点 { XmlNodeList KeyNameArr = element.ChildNodes;//子节点名称数组 if (KeyNameArr.Count > ) { foreach (XmlElement xmlElement in KeyNameArr) { //找到键值,修改为想要修改的值 if (xmlElement.Attributes["key"].InnerXml.Equals(key)) { xmlElement.Attributes["value"].Value = value; ConfigurationManager.RefreshSection("appSettings"); return true; } } //没有相应的节点 return false; } else { //不存在 AppSettings 节点 return false; } } } return false; }
-
PathHelper 【路径帮助类】
通过 System.Web.Hosting.HostingEnvironment.MapPath() 方法将虚拟路径转换为物理路径
/// <summary>
/// 将虚拟路径转换为物理路径
/// </summary>
/// <param name="virtualPath">虚拟路径</param>
/// <returns>虚拟路径对应的物理路径</returns>
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.XmlConfigurator.Configure();
} 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,浏览器类型、操作系统等信息)
#region 编码 /// <summary>
/// HTML解码
/// </summary>
/// <returns></returns>
public static string HtmlDecode(string s)
{
return HttpUtility.HtmlDecode(s);
} /// <summary>
/// HTML编码
/// </summary>
/// <returns></returns>
public static string HtmlEncode(string s)
{
return HttpUtility.HtmlEncode(s);
} /// <summary>
/// URL解码
/// </summary>
/// <returns></returns>
public static string UrlDecode(string s)
{
return HttpUtility.UrlDecode(s);
} /// <summary>
/// URL编码
/// </summary>
/// <returns></returns>
public static string UrlEncode(string s)
{
return HttpUtility.UrlEncode(s);
} #endregion 编码#region Cookie /// <summary>
/// 删除指定名称的Cookie
/// </summary>
/// <param name="name">Cookie名称</param>
public static void DeleteCookie(string name)
{
HttpCookie cookie = new HttpCookie(name);
cookie.Expires = DateTime.Now.AddYears(-);
HttpContext.Current.Response.AppendCookie(cookie);
} /// <summary>
/// 获得指定名称的Cookie值
/// </summary>
/// <param name="name">Cookie名称</param>
/// <returns></returns>
public static string GetCookie(string name)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
if (cookie != null)
return cookie.Value; return string.Empty;
} /// <summary>
/// 获得指定名称的Cookie中特定键的值
/// </summary>
/// <param name="name">Cookie名称</param>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetCookie(string name, string key)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
if (cookie != null && cookie.HasKeys)
{
string v = cookie[key];
if (v != null)
return v;
} return string.Empty;
} /// <summary>
/// 设置指定名称的Cookie的值
/// </summary>
/// <param name="name">Cookie名称</param>
/// <param name="value">值</param>
public static void SetCookie(string name, string value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
if (cookie != null)
cookie.Value = value;
else
cookie = new HttpCookie(name, value); HttpContext.Current.Response.AppendCookie(cookie);
} /// <summary>
/// 设置指定名称的Cookie的值
/// </summary>
/// <param name="name">Cookie名称</param>
/// <param name="value">值</param>
/// <param name="expires">过期时间</param>
public static void SetCookie(string name, string value, double expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
if (cookie == null)
cookie = new HttpCookie(name); cookie.Value = value;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
} /// <summary>
/// 设置指定名称的Cookie特定键的值
/// </summary>
/// <param name="name">Cookie名称</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
public static void SetCookie(string name, string key, string value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
if (cookie == null)
cookie = new HttpCookie(name); cookie[key] = value;
HttpContext.Current.Response.AppendCookie(cookie);
} /// <summary>
/// 设置指定名称的Cookie特定键的值
/// </summary>
/// <param name="name">Cookie名称</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="expires">过期时间</param>
public static void SetCookie(string name, string key, string value, double expires)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[name];
if (cookie == null)
cookie = new HttpCookie(name); cookie[key] = value;
cookie.Expires = DateTime.Now.AddMinutes(expires);
HttpContext.Current.Response.AppendCookie(cookie);
} #endregion Cookie//浏览器列表
private static string[] _browserlist = new string[] { "ie", "chrome", "mozilla", "netscape", "firefox", "opera", "konqueror" }; #region 客户端信息 /// <summary>
/// 是否是get请求
/// </summary>
/// <returns></returns>
public static bool IsGet()
{
return HttpContext.Current.Request.HttpMethod == "GET";
} /// <summary>
/// 是否是post请求
/// </summary>
/// <returns></returns>
public static bool IsPost()
{
return HttpContext.Current.Request.HttpMethod == "POST";
} /// <summary>
/// 是否是Ajax请求
/// </summary>
/// <returns></returns>
public static bool IsAjax()
{
return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
} /// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetQueryString(string key, string defaultValue)
{
string value = HttpContext.Current.Request.QueryString[key];
if (!string.IsNullOrWhiteSpace(value))
return value;
else
return defaultValue;
} /// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetQueryString(string key)
{
return GetQueryString(key, "");
} /// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetQueryInt(string key, int defaultValue)
{
return ConverterHelper.StringToInt(HttpContext.Current.Request.QueryString[key], defaultValue);
} /// <summary>
/// 获得查询字符串中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static int GetQueryInt(string key)
{
return GetQueryInt(key, );
} /// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetFormString(string key, string defaultValue)
{
string value = HttpContext.Current.Request.Form[key];
if (!string.IsNullOrWhiteSpace(value))
return value;
else
return defaultValue;
} /// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetFormString(string key)
{
return GetFormString(key, "");
} /// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetFormInt(string key, int defaultValue)
{
return ConverterHelper.StringToInt(HttpContext.Current.Request.Form[key], defaultValue);
} /// <summary>
/// 获得表单中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static int GetFormInt(string key)
{
return GetFormInt(key, );
} /// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetRequestString(string key, string defaultValue)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormString(key, defaultValue);
else
return GetQueryString(key, defaultValue);
} /// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static string GetRequestString(string key)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormString(key);
else
return GetQueryString(key);
} /// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetRequestInt(string key, int defaultValue)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormInt(key, defaultValue);
else
return GetQueryInt(key, defaultValue);
} /// <summary>
/// 获得请求中的值
/// </summary>
/// <param name="key">键</param>
/// <returns></returns>
public static int GetRequestInt(string key)
{
if (HttpContext.Current.Request.Form[key] != null)
return GetFormInt(key);
else
return GetQueryInt(key);
} /// <summary>
/// 获得上次请求的url
/// </summary>
/// <returns></returns>
public static string GetUrlReferrer()
{
Uri uri = HttpContext.Current.Request.UrlReferrer;
if (uri == null)
{
return string.Empty;
}
return uri.ToString();
} /// <summary>
/// 获得请求的主机部分
/// </summary>
/// <returns></returns>
public static string GetHost()
{
return HttpContext.Current.Request.Url.Host;
} /// <summary>
/// 获得请求的url
/// </summary>
/// <returns></returns>
public static string GetUrl()
{
return HttpContext.Current.Request.Url.ToString();
} /// <summary>
/// 获得请求的原始url
/// </summary>
/// <returns></returns>
public static string GetRawUrl()
{
return HttpContext.Current.Request.RawUrl;
} /// <summary>
/// 获得请求的ip
/// </summary>
/// <returns></returns>
public static string GetIP()
{
string ip = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
else
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); if (string.IsNullOrEmpty(ip) || !ValidateHelper.IsIP(ip))
ip = "127.0.0.1";
return ip;
} /// <summary>
/// 获得请求的浏览器类型
/// </summary>
/// <returns></returns>
public static string GetBrowserType()
{
string type = HttpContext.Current.Request.Browser.Type;
if (string.IsNullOrEmpty(type) || type == "unknown")
return "未知"; return type.ToLower();
} /// <summary>
/// 获得请求的浏览器名称
/// </summary>
/// <returns></returns>
public static string GetBrowserName()
{
string name = HttpContext.Current.Request.Browser.Browser;
if (string.IsNullOrEmpty(name) || name == "unknown")
return "未知"; return name.ToLower();
} /// <summary>
/// 获得请求的浏览器版本
/// </summary>
/// <returns></returns>
public static string GetBrowserVersion()
{
string version = HttpContext.Current.Request.Browser.Version;
if (string.IsNullOrEmpty(version) || version == "unknown")
return "未知"; return version;
} /// <summary>
/// 获得请求客户端的操作系统类型
/// </summary>
/// <returns></returns>
public static string GetOSType()
{
string userAgent = HttpContext.Current.Request.UserAgent;
if (userAgent == null)
return "未知"; string type = null;
if (userAgent.Contains("NT 6.1"))
type = "Windows 7";
else if (userAgent.Contains("NT 5.1"))
type = "Windows XP";
else if (userAgent.Contains("NT 6.2"))
type = "Windows 8";
else if (userAgent.Contains("android"))
type = "Android";
else if (userAgent.Contains("iphone"))
type = "IPhone";
else if (userAgent.Contains("Mac"))
type = "Mac";
else if (userAgent.Contains("NT 6.0"))
type = "Windows Vista";
else if (userAgent.Contains("NT 5.2"))
type = "Windows 2003";
else if (userAgent.Contains("NT 5.0"))
type = "Windows 2000";
else if (userAgent.Contains(""))
type = "Windows 98";
else if (userAgent.Contains(""))
type = "Windows 95";
else if (userAgent.Contains("Me"))
type = "Windows Me";
else if (userAgent.Contains("NT 4"))
type = "Windows NT4";
else if (userAgent.Contains("Unix"))
type = "UNIX";
else if (userAgent.Contains("Linux"))
type = "Linux";
else if (userAgent.Contains("SunOS"))
type = "SunOS";
else
type = "未知"; return type;
} /// <summary>
/// 获得请求客户端的操作系统名称
/// </summary>
/// <returns></returns>
public static string GetOSName()
{
string name = HttpContext.Current.Request.Browser.Platform;
if (string.IsNullOrEmpty(name))
return "未知"; return name;
} /// <summary>
/// 判断是否是浏览器请求
/// </summary>
/// <returns></returns>
public static bool IsBrowser()
{
string name = GetBrowserName();
foreach (string item in _browserlist)
{
if (name.Contains(item))
return true;
}
return false;
} /// <summary>
/// 是否是移动设备请求
/// </summary>
/// <returns></returns>
public static bool IsMobile()
{
if (HttpContext.Current.Request.Browser.IsMobileDevice)
return true; bool isTablet = false;
if (bool.TryParse(HttpContext.Current.Request.Browser["IsTablet"], out isTablet) && isTablet)
return true; return false;
} /// <summary>
/// 判断是否是搜索引擎爬虫请求
/// </summary>
/// <returns></returns>
public static bool IsCrawler()
{
bool result = HttpContext.Current.Request.Browser.Crawler;
if (!result)
{
string referrer = GetUrlReferrer();
if (referrer.Length > )
{
foreach (string item in _searchenginelist)
{
if (referrer.Contains(item))
return true;
}
}
}
return result;
} #endregion 客户端信息 -
ConverterHelper 【类型转换帮助类】
Json类型数据的转换是通过开源类库Json.Net来实现,利用反射将DataTable对象转换为List对象,字符串转换为其他常用类型
/// <summary>
/// 类型转换助手
/// </summary>
public static class ConverterHelper
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt">DataTable 对象</param>
/// <returns></returns>
public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
{
// 定义集合
List<T> ts = new List<T>(); // 获得此模型的类型
Type type = typeof(T);
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//将属性名称赋值给临时变量
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//对象添加到泛型集合中
ts.Add(t);
} return ts;
} /// <summary>
/// 将object对象转换为Json数据
/// </summary>
/// <param name="obj">object对象</param>
/// <returns>转换后的json字符串</returns>
public static string ObjectToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
} /// <summary>
/// 将Json对象转换为T对象
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
/// <param name="jsonString">json对象字符串</param>
/// <returns>由字符串转换得到的T对象</returns>
public static T JsonToObject<T>(string jsonString)
{
return JsonConvert.DeserializeObject<T>(jsonString);
} /// <summary>
/// 从字符串中获取数据
/// </summary>
/// <param name="content">源字符串</param>
/// <returns>字符串中的值</returns>
public static string GetContent(string content)
{
return (String.IsNullOrEmpty(content) ? null : content);
} /// <summary>
/// 将int转换为bool类型
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool ConvertIntToBool(int value)
{
return (value > ? true : false);
} #region 转Int /// <summary>
/// 将string类型转换成int类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int StringToInt(string s, int defaultValue)
{
if (!string.IsNullOrWhiteSpace(s))
{
int result;
if (int.TryParse(s, out result))
return result;
} return defaultValue;
} /// <summary>
/// 将string类型转换成int类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <returns></returns>
public static int StringToInt(string s)
{
return StringToInt(s, );
} /// <summary>
/// 将object类型转换成int类型
/// </summary>
/// <param name="s">目标对象</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int ObjectToInt(object o, int defaultValue)
{
if (o != null)
return StringToInt(o.ToString(), defaultValue); return defaultValue;
} /// <summary>
/// 将object类型转换成int类型
/// </summary>
/// <param name="s">目标对象</param>
/// <returns></returns>
public static int ObjectToInt(object o)
{
return ObjectToInt(o, );
} #endregion 转Int #region 转Bool /// <summary>
/// 将string类型转换成bool类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static bool StringToBool(string s, bool defaultValue)
{
if (s.ToLower().Equals("false"))
return false;
else if (s.ToLower().Equals("true"))
return true; return defaultValue;
} /// <summary>
/// 将string类型转换成bool类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <returns></returns>
public static bool ToBool(string s)
{
return StringToBool(s, false);
} /// <summary>
/// 将object类型转换成bool类型
/// </summary>
/// <param name="s">目标对象</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static bool ObjectToBool(object o, bool defaultValue)
{
if (o != null)
return StringToBool(o.ToString(), defaultValue); return defaultValue;
} /// <summary>
/// 将object类型转换成bool类型
/// </summary>
/// <param name="s">目标对象</param>
/// <returns></returns>
public static bool ObjectToBool(object o)
{
return ObjectToBool(o, false);
} #endregion 转Bool #region 转DateTime /// <summary>
/// 将string类型转换成datetime类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static DateTime StringToDateTime(string s, DateTime defaultValue)
{
if (!string.IsNullOrWhiteSpace(s))
{
DateTime result;
if (DateTime.TryParse(s, out result))
return result;
}
return defaultValue;
} /// <summary>
/// 将string类型转换成datetime类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <returns></returns>
public static DateTime StringToDateTime(string s)
{
return StringToDateTime(s, DateTime.Now);
} /// <summary>
/// 将object类型转换成datetime类型
/// </summary>
/// <param name="s">目标对象</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static DateTime ObjectToDateTime(object o, DateTime defaultValue)
{
if (o != null)
return StringToDateTime(o.ToString(), defaultValue); return defaultValue;
} /// <summary>
/// 将object类型转换成datetime类型
/// </summary>
/// <param name="s">目标对象</param>
/// <returns></returns>
public static DateTime ObjectToDateTime(object o)
{
return ObjectToDateTime(o, DateTime.Now);
} #endregion 转DateTime #region 转Decimal /// <summary>
/// 将string类型转换成decimal类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static decimal StringToDecimal(string s, decimal defaultValue)
{
if (!string.IsNullOrWhiteSpace(s))
{
decimal result;
if (decimal.TryParse(s, out result))
return result;
} return defaultValue;
} /// <summary>
/// 将string类型转换成decimal类型
/// </summary>
/// <param name="s">目标字符串</param>
/// <returns></returns>
public static decimal StringToDecimal(string s)
{
return StringToDecimal(s, 0m);
} /// <summary>
/// 将object类型转换成decimal类型
/// </summary>
/// <param name="s">目标对象</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static decimal ObjectToDecimal(object o, decimal defaultValue)
{
if (o != null)
return StringToDecimal(o.ToString(), defaultValue); return defaultValue;
} /// <summary>
/// 将object类型转换成decimal类型
/// </summary>
/// <param name="s">目标对象</param>
/// <returns></returns>
public static decimal ObjectToDecimal(object o)
{
return ObjectToDecimal(o, 0m);
} #endregion 转Decimal
}
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
- 添加类库引用
-
创建Entity
创建一个类,继承DbContext类,并在他的构造函数中设置连接字符串或者构造函数中传递配置文件中ConnectionStrings的name
-
创建数据模型models
创建Web应用中用到的Model对应数据库中的表,ViewModel另外设置,这里的models对应数据库的数据表,User示例:
-
启用数据迁移 EnableMigration
- 打开 Package Manager Console
- 执行命令 "Enable-Migrations",如果这个项目中有两个或两个以上的继承DbContext类的Entity,需要制定Context的名称,不然会提示有多个Context。
-
执行命令之后会生成一个 Migrations文件夹,文件夹下有一个Configuration文件,打开文件修改构造函数,设置 AutomaticMigrationsEnabled = true;