Asp.net MVC 简单入门
年前一直想写个系列教程来完整的过一下Asp.NET MVC,同时也可以帮助一些人来避免我在工作中遇到的坑,碰过的壁。缘于能力有限,时间也不充足,一直也没有能实现,幸好看到 Marla Sukesh 写了个7天教程,讲的挺好,就想顺便翻译过来給各位,英文水平有限,请各位多多包涵。
菜鸟,请主动动手,不段动手才会发现问题。
大神,请留下宝贵的看法。
有问题或建议尽管提。
今天先简单用”Code First”的模式基于 EF5, MVC4 和 MVC Scaffolding(脚手架->通过Nuget安装)创建一个简单的图书管理系统来热身, 数据库我们就选择微软自家的SQL Server2012了:
环境如下: Win7 with sp1 and VS2012
步骤1:创建一个以Razor为引擎的互联网应用程序:
步骤2:安装EntityFramework
安装EntityFramework:
PM>Install-PackageEntityFramework
安装MvcScaffolding
PM>Install-PackageMvcScaffoldingAttemptingtoresolvedependency'T4Scaffolding'.Attemptingtoresolvedependency'T4Scaffolding.Core'.Attemptingtoresolvedependency'EntityFramework'.Installing'T4Scaffolding.Core1.0.0'.Successfullyinstalled'T4Scaffolding.Core1.0.0'.Installing'T4Scaffolding1.0.8'.Successfullyinstalled'T4Scaffolding1.0.8'.Installing'MvcScaffolding1.0.9'.Successfullyinstalled'MvcScaffolding1.0.9'.
既然是code first,那么下来自然就是要来创建Models了:
在Models的文件夹中创建三个实体类:
///<summary>///BookEntity///</summary>publicclassBook{[Key]publicintID{get;set;}publicstringBookName{get;set;}///<summary>///OnetoOne///</summary>publicintPublisherID{get;set;}[ForeignKey("PublisherID")]publicvirtualPublisherPublisher{get;set;}///<summary>///OnetoMany///</summary>publicvirtualICollection<Author>Authors{get;set;}}///<summary>///AuthorEntity///</summary>publicclassAuthor{[Key]publicintID{get;set;}publicstringAuthorName{get;set;}publicintBookID{get;set;}}///<summary>///PublisherEntity///</summary>publicclassPublisher{[Key]publicintID{get;set;}publicstringPublisherName{get;set;}}
建三个实体类对应的Mvc View---空View就好.
然后打开Package Manager Console, 运行下面的命令:
PM>ScaffoldControllerBookPM>ScaffoldControllerAuthorPM>ScaffoldControllerPublisher
如果要通过Repository访问数据那么要在最后加上一个参数:–Repository
像:
PM>ScaffoldControllerBook–Repository
如果要重新生成对应的view和Controller那么再加一个参数:-Force
像:
PM>ScaffoldControllerBook–Repository–Force
然后你会得到的结果如下:
神奇吧,自动就帮你生成了通用部分的View,与数据库交互的Repository, Controller以及比较重要的FirstMouseContext,省心省力。FirstMouseContext
我们来配置下让自动创建的东西,显示出来,编辑Shared/_Layout.cshtml,添加一个链接进去,这样好导航到我们view里, 如:
<li>@Html.ActionLink("Books","Index","Books")</li><li>@Html.ActionLink("Authors","Index","Authors")</li><li>@Html.ActionLink("Publishers","Index","Publishers")</li>
得到了下面的错误信息:
我们修改外键为可空,重新跑一次:
PM>ScaffoldControllerBook-Repository-ForcePM>ScaffoldControllerAuthor-Repository-ForcePM>ScaffoldControllerPublisher-Repository–Force
运行起来,又错了:
明显的忘记配置数据库信息了,找到配置文件Web.config
<addname="DefaultConnection"connectionString="….”>
修改为:
<addname="FirstMouseContext"connectionString="….”>
再次启动,正常了:
还有一点儿要捎带注意的是 DbContext:
publicclassFirstMouseContext:DbContext{//Youcanaddcustomcodetothisfile.Changeswillnotbeoverwritten.////IfyouwantEntityFrameworktodropandregenerateyourdatabase//automaticallywheneveryouchangeyourmodelschema,addthefollowing//codetotheApplication_StartmethodinyourGlobal.asaxfile.//Note:thiswilldestroyandre-createyourdatabasewitheverymodelchange.////System.Data.Entity.Database.SetInitializer(newSystem.Data.Entity.DropCreateDatabaseIfModelChanges<FirstMouse.Models.FirstMouseContext>());publicDbSet<FirstMouse.Models.Book>Books{get;set;}publicDbSet<FirstMouse.Models.Author>Authors{get;set;}publicDbSet<FirstMouse.Models.Publisher>Publishers{get;set;}}
看到解释了吧?大概意思是说,如果你的Model的Schema有变化的时侯,如果想要重新生成数据库,那么就应该把下面的一句加在Global.asax文件里:
publicclassMvcApplication:System.Web.HttpApplication{protectedvoidApplication_Start(){AreaRegistration.RegisterAllAreas();WebApiConfig.Register(GlobalConfiguration.Configuration);FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);AuthConfig.RegisterAuth();System.Data.Entity.Database.SetInitializer(newSystem.Data.Entity.DropCreateDatabaseIfModelChanges<FirstMouse.Models.FirstMouseContext>());}}
实际上你也可以放在构造函数里:
publicFirstMouseContext(){System.Data.Entity.Database.SetInitializer(newSystem.Data.Entity.DropCreateDatabaseIfModelChanges<FirstMouse.Models.FirstMouseContext>());}
很好很强大吧?准备好精力迎接下周的密集知识点儿轰炸吧…
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。