MVC Code First

Source: Internet
Author: User

first configure the Web. config

  <connectionStrings>    <add name= "Bookdbcontext" connectionstring= "Data source=.\sqlexpress;initial Catalog=sales; Persist Security info=true;integrated security=sspi; "     Providername= "System.Data.SqlClient"/>  </connectionStrings>

then add a book class and a Bookdbcontext class to the model

Book class

Using system;using system.collections.generic;using system.linq;using system.web;namespace MvcApplication3.Models{ public class book    {public        int BookID {get; set;}        public string BookName {get; set;}        public string Author {get; set;}        public string Publisher {get; set;}        Public decimal price {get; set;}        public string Remark {get; set;}}    }

Bookdbcontext class

Using system;using system.collections.generic;using system.linq;using system.web;using System.Data.Entity;namespace mvcapplication3.models{//<summary>//    Bookdbcontext Represents the context object of the book in the database in EF, through dbset<book> Associates the entity class with the database. The Books property represents the dataset entity in the database and is used to process data access and updates. Bookdbcontext derived from DbContext, you need to add a reference to System.Data.Entity.    //</summary> public    class Bookdbcontext:dbcontext    {        ///<summary>///= for run creation, The typed entity set for read, update, and delete operations.

DbSet are not publicly available. Can only be created from System.Data.Entity.DbContext instances. // </summary> public dbset<book> Books {get; set;}} }

Add a book controller

To understand FormCollection, please refer to: FormCollection Pass Value

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using        Mvcapplication3.models;namespace mvcapplication3.controllers{public class Bookcontroller:controller {//        GET:/book/bookdbcontext db = new Bookdbcontext (); <summary>//////Find out all the book objects, make up a books, let it show on the page first///</summary>//&LT;RETURNS&GT;&L T;/returns> public ActionResult Index () {//This is a simple LINQ query when operating against a database. EF checks whether the database specified by the current data connection is created, assuming that no EF is responsible for creating a database, a data table from the entity model class, and if so, EF adds the query criteria to the SQL query statement and then sends the SQL statement to the database for data read. After the data is read, the data is converted to a collection of entity objects.

EF operates on the database roughly so var books = from B in db. Books Select B; Return View (books. ToList ()); } [HttpGet] public ActionResult Create () {return View (); } [HttpPost] public ActionResult Create (book book) {//MVC validation All properties Verify success Modelstate.isvalid equals t Rue, just to have a validation unsuccessful modelstate.isvalid is equal to false so we can infer the validity of the data through this property, but sometimes we don't need to validate all the data when validating the data. For example, you only need to verify that username and password formats are entered correctly when logging in. Use the following method to exclude the field to be validated: Modelstate.remove ("email"), not verifying email. So email this field will not be verified, email verification does not pass the value of Modelstate.isvalid is still true if (Modelstate.isvalid) {db . Books.add (book); Db. SaveChanges (); Return redirecttoaction ("Index"); } else {return View (book); }} [HttpGet] public actionresult Delete (int id) {var data = from DataItem in db.b Ooks where DAtaitem.bookid = = ID Select DataItem; Viewdata.model = data. Single (); return View (); } [HttpPost] public actionresult Delete (int id, formcollection c)//In fact this formcollection C is converted to int a=5 or int A=6 are all capable. Just make sure that the Delete method differs from the Delete method parameter above.

The

is actually a guarantee that the two methods that make up the overload {//find () return the first element that satisfies the condition, assuming that there is no element, then NULL is returned.

Book book = db. Books.find (ID); can also be written: Book book=db. Books.firstordefault (d=>d.bookid==id) db. Books.remove (book); Db. SaveChanges (); Return redirecttoaction ("Index"); Public ActionResult Edit (int id) {//var data = from DataItem in db. Books//Where DataItem. BookID = = ID//select DataItem; Viewdata.model = data. Single (); return View (); Find () is a book that returns the first element that satisfies the condition (that is, the book with the ID of BookID in books), assuming that there is no element. Then NULL is returned. Book book = db. Books.find (ID); if (book = = null) {return redirecttoaction ("Index"); } return View (book); } [HttpPost] public actionresult Edit (book Newbook) {try {Book Oldbook = db. Books.find (Newbook. BookID); Updates the specified model instance Updatemodel (old) using the value of the current value provider from the controllerbook); Saves all changes made in this context to the underlying database.

Db. SaveChanges (); Return redirecttoaction ("Index"); } catch (Exception ex) {//addmodelerror: Adds the specified error message to the error collection of the model-state dictionary associated with the specified key. Modelstate.addmodelerror ("", "Change failed. Please see the specific error message "+ Ex. Message + ex. StackTrace); } return View (Newbook); The public actionresult Details (int id) {//find () returns the first element that satisfies the condition (that is, the book with the ID of the BookID in books), assuming that the element is not , NULL is returned. Book book = db. Books.find (ID); if (book = = null) {return redirecttoaction ("Index"); } return View (book); } }}



View

Index View Home

@model ienumerable<mvcapplication3.models.book>@{viewbag.title = "book List-mvcbook";} 

Create

@model mvcapplication3.models.book@{viewbag.title = "Create";} 

Delete

@model mvcapplication3.models.book@{viewbag.title = "Delete";} 

Edit

@model mvcapplication3.models.book@{viewbag.title = "Edit";} 

Details

 @model mvcapplication3.models.book@{viewbag.title = "Details";} 


Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

MVC Code First

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.