日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯網營銷解決方案
詳解ASP.NETMVC對表進行通用的增刪改

作者的寫下此文的背景是一些項目本身規(guī)模不大的情況下,也有其他網友擔心性能方面的問題。在這里我們先看一下ASP.NET MVC對表是如何進行通用的增刪改操作的。

創(chuàng)新互聯于2013年創(chuàng)立,先為黃巖等服務建站,黃巖等地企業(yè),進行企業(yè)商務咨詢服務。為黃巖企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。

預備知識:

1、了解反射技術

2、了解C#3.0中擴展方法,分布類,Linq to object,Linq to sql

3、了解ASP.NET MVC

在項目中每添加一個表往往都要添加一套增刪改代碼,而且這些代碼很多情況下都很相似,這里我們給出一個通用的解決方案供大家參考。

一、準備工作:

這里我們先要在數據庫中添加兩個表News和User如下圖:然后拖到dbml中生成實體類。

這里我們先準備一個接口:ICommonTable

 
 
 
  1. Code  
  2. public  interface ICommonTable  
  3. {  
  4. int id { getset; }  

然后讓News和User實體都繼承于此接口

 
 
 
  1. Code  
  2. public partial class News : ICommonTable  
  3. {  
  4. }  
  5. public partial class User : ICommonTable  
  6. {  

二、通用刪除操作

分別添加NewsList.aspx和UserList.aspx兩個view,添加方式參見ASP.NET MVC實踐系列2-簡單應用

在這兩個View中加入刪除鏈接:

 
 
 
  1. <%= Html.ActionLink("刪除", "Delete", new { key = item.id, partialName="News" })%> 
  2. 和  
  3. <%= Html.ActionLink("刪除", "Delete", new { key = item.id, partialName="User" })%> 

然后添加一個Controller:

 
 
 
  1. public ActionResult Delete(string partialName, int? key)  
  2. {  
  3. RepositoryBase repositoryBase = new RepositoryBase(partialName);  
  4. repositoryBase.Delete(key ?? 0);  
  5. return RedirectToAction(partialName + "List");//返回到list  

接下來我們介紹一下RepositoryBase :

 
 
 
  1. public class RepositoryBase  
  2. {  
  3. public Type EntityType { getprivate set; }  
  4. public RepositoryBase(string entityType)  
  5. {  
  6. Type type = GetBllTypeByName(entityType);  
  7.  
  8. EntityType = type;  
  9. }  
  10. public ICommonTable CreateNew()  
  11. {  
  12. return (ICommonTable)Activator.CreateInstance(EntityType);  
  13. }  
  14. ///   
  15. /// 通過字符串獲得其Type  
  16. ///   
  17. ///   
  18. ///   
  19. private static Type GetBllTypeByName(string typeName)  
  20. {  
  21. Type type = null;  
  22. var ass = AppDomain.CurrentDomain.GetAssemblies()  
  23. .Where(p => p.FullName.Contains("CommonCEDemo"));  
  24. foreach (var a in ass)  
  25. {  
  26. type = a.GetTypes().Where(p => p.Name == typeName).FirstOrDefault();  
  27. if (type != null)  
  28. break;  
  29. }  
  30.  
  31. if (type == null)  
  32. {  
  33. throw new Exception("類型未定義:" + typeName);  
  34. }  
  35. return type;  
  36. }  
  37. public RepositoryBase(Type entityType)  
  38. {  
  39. EntityType = entityType;  
  40. }  
  41. public ICommonTable Get(int id)  
  42. {  
  43. DBDataContext db = Context.GetContext();  
  44. return db.GetTable(EntityType).Cast().FirstOrDefault(p => p.id == id);  
  45. }  
  46. public void Delete(int id)  
  47. {  
  48. ICommonTable bllTable = Get(id);  
  49. Context.GetContext().GetTable(EntityType).DeleteOnSubmit(bllTable);  
  50. Context.GetContext().SubmitChanges();  
  51. }  

這里邊重點要理解的就是GetBllTypeByName方法。有了這個方法我們就可以動態(tài)的通過名字獲得相應的Type了。這里還有個問題就是DataContext是從何而來的,我們這里為了簡單起見全程聲明了一個DataContext沒有考慮多線程的情況

 
 
 
  1. public class Context  
  2. {  
  3. static DBDataContext context;  
  4. static Context()  
  5. {  
  6. if (context==null)  
  7. {  
  8. context = new DBDataContext();  
  9. }  
  10. }  
  11. public static DBDataContext GetContext()  
  12. {  
  13. return context;  
  14. }  

有個這些當我們想要對一個表進行刪除是只要添加相應的鏈接就可以了(如<%= Html.ActionLink("刪除", "Delete", new { key = item.id, partialName="News" })%>)

三、通用增加、修改

首先添加一個CreateEditView.aspx視圖

 
 
 
  1.  ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
  2. <%Html.RenderPartial(ViewData["PartialName"].ToString()); %> 
  3.  

然后添加兩個Partial視圖News.ascx和User.ascx,這兩個視圖是分別基于News和User類的強類型視圖,具體內容參加源碼。
接下來我們添加相應的Controller

 
 
 
  1. public ActionResult CreateEditView(string partialName, int? key)  
  2. {  
  3. ViewData["PartialName"] = partialName;  
  4. RepositoryBase repositoryBase = new RepositoryBase(partialName);  
  5. ICommonTable table;  
  6. if (key == null)  
  7. {  
  8. table = repositoryBase.CreateNew();  
  9. }  
  10. else 
  11. {  
  12. table = repositoryBase.Get(key ?? 0);  
  13. }  
  14.  
  15. return View("CreateEditView", table);  
  16. }  
  17. [AcceptVerbs(HttpVerbs.Post)]  
  18. public ActionResult CreateEditView(string partialName, int? key, FormCollection formCollection)  
  19. {  
  20. RepositoryBase repositoryBase = new RepositoryBase(partialName);  
  21. ICommonTable bllTable;  
  22. if (key == null)  
  23. {  
  24. bllTable = repositoryBase.CreateNew();  
  25. }  
  26. else 
  27. {  
  28. bllTable = repositoryBase.Get(key ?? 0);  
  29. }  
  30. this.UpdateModel(bllTable, true);  
  31. if (key == null)  
  32. {  
  33. Context.GetContext().GetTable(repositoryBase.EntityType).InsertOnSubmit(bllTable);  
  34. }  
  35. Context.GetContext().SubmitChanges();  
  36. return RedirectToAction(partialName+"List");//返回到list  

這里邊大家可能有疑問的就是this.UpdateModel(bllTable, true);這個方法在mvc框架中并不存在,這是我添加的擴展方法,這個地方如果使用UpdateModel(bllTable)雖然編譯不會報錯,但也沒有更新成功,查了一下mvc的源碼,問題就出在如下源碼中:

 
 
 
  1. protected internal bool TryUpdateModel(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IDictionary<string, ValueProviderResult> valueProvider) where TModel : class {  
  2. if (model == null) {  
  3. throw new ArgumentNullException("model");  
  4. }  
  5. if (valueProvider == null) {  
  6. throw new ArgumentNullException("valueProvider");  
  7. }  
  8.  
  9. Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);  
  10. IModelBinder binder = Binders.GetBinder(typeof(TModel));  
  11.  
  12. ModelBindingContext bindingContext = new ModelBindingContext() {  
  13. Model = model,  
  14. ModelName = prefix,  
  15. ModelState = ModelState,  
  16. ModelType = typeof(TModel),  
  17. PropertyFilter = propertyFilter,  
  18. ValueProvider = valueProvider  
  19. };  
  20. binder.BindModel(ControllerContext, bindingContext);  
  21. return ModelState.IsValid;  

這個typeof(TModel)造成了只會更新聲明類型中有的屬性,把它換成model.GetType()就可以解決問題了,我擴這的這個方法如下

 
 
 
  1. public static class ControllerExtension  
  2. {  
  3. ///   
  4. /// 更新時是否按照當前類型進行更新  
  5. ///   
  6. ///   
  7. ///   
  8. ///   
  9. ///   
  10. public static void UpdateModel(this Controller controller, TModel model, bool isExtension) where TModel : class 
  11. {  
  12. if (isExtension)  
  13. {  
  14. Predicate<string> propertyFilter = propertyName => IsPropertyAllowed(propertyName, nullnull);  
  15. IModelBinder binder = ModelBinders.Binders.GetBinder(model.GetType());  
  16.  
  17. ModelBindingContext bindingContext = new ModelBindingContext()  
  18. {  
  19. Model = model,  
  20. ModelName = null,  
  21. ModelState = controller.ModelState,  
  22. ModelType = model.GetType(),  
  23. PropertyFilter = propertyFilter,  
  24. ValueProvider = controller.ValueProvider  
  25. };  
  26. binder.BindModel(controller.ControllerContext, bindingContext);  
  27.  
  28. }  
  29. else 
  30. {  
  31. throw new Exception("isExtension不能選擇false");  
  32. }  
  33. }  
  34. private static bool IsPropertyAllowed(string propertyName, string[] includeProperties, string[] excludeProperties)  
  35. {  
  36. bool includeProperty = (includeProperties == null) || (includeProperties.Length == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);  
  37. bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);  
  38. return includeProperty && !excludeProperty;  
  39. }  

有了這些,當我們想對新表進行編輯和添加時只需要添加相應的Partial編輯視圖就可以了,簡化了我們的編程工作。

四、缺點

1、須要按照規(guī)則命名,比方說Partial視圖需要以相應的類名來命名

2、頁面引用是弱類型的


分享文章:詳解ASP.NETMVC對表進行通用的增刪改
分享URL:http://www.dlmjj.cn/article/cohddpj.html