MVC5学习系列——添加模型(Model)、链接字符串
来源:互联网 发布:开心保健康保 知乎 编辑:程序博客网 时间:2024/05/22 03:38
MVC5学习笔记,其实就是敲了一遍官网代码,官网地址:http://www.asp.net/mvc
接着上一篇MVC5学习系列——添加视图,这次我们添加模型(Model)。
我们给Movie类添加几个属性:
public class Movie { public int ID { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string Genre { get; set; } public decimal Price { get; set; } }紧接着我们在Models中在创建一个类:MVC5TestDBContext.cs
public class MVC5TestDBContext : DbContext { public DbSet<Movie> Movies { get; set; } }我们发现下面的问题:
我晕了,竟然没有找到。按照官网提示添加 using System.Data.Entity; 还是不行;就算添加System.Data.Entity 引用,还是不行:
最后发现问题在这里,赶紧安装啊!安装成功之后:
终于有了,快点添加吧!
我们再看看Web.config中的变化,之前:
<?xml version="1.0" encoding="utf-8"?><!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301880 --><configuration> <appSettings> <add key="webpages:Version" value="3.0.0.0"/> <add key="webpages:Enabled" value="false"/> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.6"/> <httpRuntime targetFramework="4.6"/> </system.web> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/> </dependentAssembly> </assemblyBinding> </runtime> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/> </compilers> </system.codedom></configuration>之后:
<?xml version="1.0" encoding="utf-8"?><!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301880 --><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.6" /> <httpRuntime targetFramework="4.6" /> </system.web> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly> </assemblyBinding> </runtime> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> </compilers> </system.codedom> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework></configuration>接下来,我们创建Movie控制器:
哈哈,要先重新生成一下,在进行上述操作,添加成功之后如下图:
看一下MovieController.cs自动生成的代码:
public class MoviesController : Controller { private MVC5TestDBContext db = new MVC5TestDBContext(); // GET: Movies public ActionResult Index() { return View(db.Movies.ToList()); } // GET: Movies/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // GET: Movies/Create public ActionResult Create() { return View(); } // POST: Movies/Create // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie) { if (ModelState.IsValid) { db.Movies.Add(movie); db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); } // GET: Movies/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // POST: Movies/Edit/5 // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie) { if (ModelState.IsValid) { db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(movie); } // GET: Movies/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie); } // POST: Movies/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Movie movie = db.Movies.Find(id); db.Movies.Remove(movie); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
我们先修改一下默认路由:
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Movies", action = "Index", id = UrlParameter.Optional } ); } }调试如下:
又出错了,对了,忘了添加Connection String字符串了:
<connectionStrings> <add name="MVC5TestDBContext" connectionString="server=.;database=MVC5TestDB;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings>再次调试,如下图:终于成功了!
在调试之前,我是没有添加MVC5TestDB数据库的。但是为什么能成功呢!
这就是传说中的代码有限吧!Code First。这篇就写到这里了。谢谢!
0 0
- MVC5学习系列——添加模型(Model)、链接字符串
- MVC5学习系列——从控制器访问模型的数据(添加、修改、删除)
- MVC5学习系列——添加视图
- MVC5学习系列—添加查询
- MVC5学习系列——HelloWorld
- 深度学习技术系列(1):Mosaic Model — 不良图片检测开源模型
- 学习ASP .NET MVC5官方教程总结(四)添加模型
- MVC5学习系列——详解编辑操作
- MVC5学习系列——排序、过滤、分页
- 【MVC5】4.添加一个模型
- 引擎系列学习【一】Color Model(颜色模型)
- Django学习笔记(三)—— 模型 model
- Hibernate学习笔记—模型类(model)的规范
- Yii2—模型(Model)
- Yii2—模型(Model)
- django系列5:模型(model)
- 机器学习入门系列05,Classification: Probabilistic Generative Model(分类:概率生成模型)
- 深度学习笔记——Attention Model(注意力模型)学习总结
- iOS 基础类解析 - NSCharacterSet___开发中判断空字符串的几种方法
- 使用Python实现端口映射
- 排序 Sorting
- xib定义的tableviewcell宽度固定,无法适配屏幕
- 【杭电】[2009]求数列的和
- MVC5学习系列——添加模型(Model)、链接字符串
- 黑马程序员——多线程
- 【杭电】[2008]数值统计
- Unity中四种坐标系
- 使用plsql 连接远程Oracle数据库
- 用gitblog建一个blog
- [BZOJ1355] [Baltic2009]Radio Transmission
- 课程总结 -- 自然语言处理
- HTML5应用之文件上传