EF 4.1+MVC3+Jquery Ajax+Json.Net+JqueryUI+IUnitOfWork+Repository 学习DEMO(暂停更新)
学习项目进行中,持续更新。
SyntaxHighlighter貌似在2011wlw里报错,无法着色。
EF记得在我搞Linq2Sql不久就放出声音出来了,说有多么多么好。
记得早先版本里尝鲜的时候我一看到那坨xml就恶心,也就没心情接着玩了。
没办法Linq2Sql里的xml就被它搞的死去活来,哎,过渡产品
本来想凭着Linq2Sql的经验不看介绍直接玩,完了,托大了,几个小时一直返回“no ProviderManifestToken string …”
好吧,认真看ADO TEAM BLOG的文章,太不负责任了,说详细点会死啊,“痛苦并快乐着”。
接着看看ScottGu,还是老大负责,烧香,行礼~
EF版本更新也太快了,不过真的是越来越方便了,要跟上时代。
毫不犹豫地选择Code-Fist 方向,一路凯歌前进。
先贴上Entity 代码:
1: [DataContract]2: public class BlogArticle3: {4: [Key]5: [Required]6: [DataMember]7: public int BlogAritcleID { get; set; }8:9: [Required(ErrorMessage="博客标题不可以为空!")]
10: [StringLength (256,ErrorMessage="博客标题最长不超过256个字符。")]
11: [DataMember]12: public string Title { get; set; }13:14: [Required(ErrorMessage="博客文章不可以为空!")]
15: [StringLength(25600,ErrorMessage="博客标题最长不超过25600个字符。")]
16: [DataMember]17: public string Article { get; set; }18:19: [Required]20: [DataMember]21: public int BlogCategoryID { get; set; }22:23: [Required]24: [DataMember]25: public DateTime PublishDate { get; set; }26:27: [Required]28: [DataMember]29: public DateTime UpdateDate { get; set; }30:31:32: public virtual BlogCategory BlogCategory { get; set; }33: }34: [DataContract]35: public class BlogCategory36: {37: [Key]38: [Required]39: [DataMember]40: public virtual int BlogCategoryID { get; set; }41:42: [Required]43: [DataMember]44: public virtual string Name { get; set; }45:46: [JsonIgnore]47: public virtual ICollection<BlogArticle> BlogArticles { get; set; }48: }
32,47两行代码使得DBContext可以对这两个表建立外键关系,神之笔啊,同理多对多也差不多。
上面DATAMEMBER等特性是Json.Net需求的,如果没有声明会在json序列化的时候报错,其中就有“RenlationshipManage”JN无法继续序列化,会引发自引用。所以这里必须用排他法标注。
接着DBContext,这个东西让我想起了Linq to sql,当时是这么个Context,看起来倍感亲切。
这个玩意儿神奇,EF就是靠它找到那些entity,烧香,行礼。
哪位老大能告诉我下面Seed里为什么数据总是添加进不去?:
1: public class BlogContext:DbContext2: {3: public DbSet<BlogArticle> BlogArticles { get; set; }4: public DbSet<BlogCategory> BlogCategories { get; set; }5:6: public BlogContext()
7: { }8: public BlogContext(string cnn)9: : base(cnn)
10: { }11:12: protected override void OnModelCreating(DbModelBuilder modelBuilder)13: {14:15: base.OnModelCreating(modelBuilder);
16: }17:18: public static void AddSeedData(BlogContext c)
这里DBSET<T>告诉DBContext哪些是要map进数据库的实体~进过这里的实体类型也会被动改变,因为他们即将拥有关系。
Application_Start
1: protected void Application_Start()2: {3: AreaRegistration.RegisterAllAreas();4:5: RegisterGlobalFilters(GlobalFilters.Filters);6: RegisterRoutes(RouteTable.Routes);7:8: Database.SetInitializer<BlogContext>(new DropCreateDatabaseIfModelChanges<BlogContext>());
9: }
第一次运行会创建相应的数据库,可以指定config中的连接字符串。
虽然没有在项目中创建EDM,实际上是放在自动创建的库中了。
然后就是做出以下两个界面以及引进JqueryUI
第一次用JqueryUI,太TMD爽了,哇哈哈~~
AJAX
客户端“删除”链接:
1: <a href="javascript:" onclick="ajaxPost('./Article/Delete?id=@item.BlogAritcleID')">Delete</a>
客户端“删除”请求:
1: <script language ="javascript" type="text/javascript" >2: function ajaxPost(urlStr) {
3: $.ajax({4: url: urlStr,5: beforeSend: function () { ShowMessage("正在提交,请等待!"); },6: success: function (data) { ShowMessage(data); setTimeout(refreshPage, 800); },7: error: function (data) { ShowMessage(data); }
8: });9: }10:11:12: </script>
2011WLW一个劲当掉,晕~~
客户端“添加”以及“编辑”请求(以BlogArticleID是否<0来区分):
1: $.ajax({2: type: "POST",
3: contentType:"application/json",
4: url:"Do",
5: data:articleStr,6: dataType:'json',7: processData:true,
8: beforeSend: function () {
9: ShowMessage("正在提交");
10: },11: success:function(data){
12: ShowMessage(data.Message);13: setTimeout(toHomePage,1000);
14: },15: error:function() {
16: ShowMessage("Your request is failed, pls check your internet and try again later!");
17: }18: });
这里用json来交互,json一直只闻其名,一直以为挺麻烦的东西没想到用起来挺顺的。
对了,谁能告诉我为什么Jquery在ajax提交的时候,datatype不是string的全要process成querystring啊?
json对象与json string的转换 articleStr=JSON.stringify(article);
服务端:
1: [HttpPost]2: public ActionResult Do()
3: {4: var entityStr=string.Empty;
5:6: //read json entity from post request
7: using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.InputStream))
8: {9: entityStr = reader.ReadToEnd();10:11: //jquery ajax process the data by utf-8, need to convert back
12: entityStr = HttpUtility.UrlDecode(entityStr);13: }14:15: //try convert to entity back
16: BlogArticle article=null;
17: ResponseState rs = new ResponseState();
18: try
19: {20:21: article = JsonConvert.DeserializeObject<BlogArticle>(22: entityStr23: , new Newtonsoft.Json.Converters.IsoDateTimeConverter())//keep the date formate same as new date in javascript24: as BlogArticle;25:26: if (article.BlogAritcleID < 0)
27: blogContext.BlogArticles.Add(article);28: else
29: {30: blogContext.BlogArticles.Attach(article);31: var stateEntry = ((IObjectContextAdapter)blogContext)
32: .ObjectContext33: .ObjectStateManager34: .GetObjectStateEntry(article);35: stateEntry.SetModifiedProperty("Title");
36: stateEntry.SetModifiedProperty("Article");
37: stateEntry.SetModifiedProperty("BlogCategoryID");
38: stateEntry.SetModifiedProperty("UpdateDate");
39: }40:41: blogContext.SaveChanges();42:43: rs.isSuccess = true;
44: rs.Message = "Submit Success!";
45: }46: catch (Exception exc)
47: {48: rs.isSuccess = false;
49: rs.Message = exc.Message;50: //rs.Message = "For some reason ,your article refused! Pls check and submit again!";
51: }52: finally
53: {54: System.Threading.Thread.Sleep(800);//wait to show ajax effect
55: Response.Clear();56: Response.Write(JsonConvert.SerializeObject(rs));//response the result
57: Response.ContentType = "application/json";
58: Response.End();59: }60:61: return new EmptyResult();//no view need62: }
对于上面更新实体部分请参考dudu文章
-----------------V1 部分结束-------------------------
加个进度条
简单做个检查防止提交频率过快
1: public static bool SubmitFreCheck()2: {3: if (CurrentContext().Session[lastSubmitTime] is DateTime)
4: {5: var date = (DateTime) CurrentContext().Session[lastSubmitTime];
6: if (date.AddSeconds(3) > DateTime.Now)
7: return true;8: }9: return false;10: }11:12: public static void SetLastSubmitDate()13: {14: CurrentContext().Session[lastSubmitTime] = DateTime.Now;15: }
1: function getPageNoprocess(size,pageIndex) {
2: $.ajax({3: type: "get",
4: url: './Article/GetArticlesByPage?size=' + size + '&pageIndex=' + pageIndex,5: dataType: "html",
6: beforeSend: function () {
7: CurrentIndex = pageIndex;8: },9: success: function (data) {
10: $('#ArticleTable tr[class="data"]').remove();11: $('#ArticleTable').append(data);12: getPagerLinks(size, pageIndex);13: }14: });15: }
服务端:
1: [HttpGet]2: public ActionResult GetArticlesByPage(int? size ,int? pageIndex)3: {4: if (size == null || size < 1)5: size = 5;6:7: if (pageIndex == null || pageIndex < 1)8: pageIndex = 1;9:10: System.Threading.Thread.Sleep(500);11:12: try
13: {14: IArticleRepository ar = new ArticleRepository(iUnitOfWork);
15:16: var eList = ar.GetEntityCollecionByPage((int)size, (int)pageIndex);17:18: string repStr = string.Empty;19: StringBuilder sb = new StringBuilder();
20: if(eList !=null )21: foreach (var e in eList)22: {23: #region table tr build up24: 。。。25: #endregion26: }27: Response.Clear();28: Response.Write(sb.ToString());29: Response.Flush();30: }31: catch (Exception exc)
32: {33: }34:35: return new EmptyResult();36: }
有列表没分页不行,来一个:
眼熟?是的,模仿博客园首页~