1.建立數據庫web
2.建立表sql
- <pre name="code" class="sql">CREATE TABLE [dbo].[Student](
- [ID] [INT] IDENTITY(1,1) NOT NULL,
- [Name] [NVARCHAR](30) NULL,
- [StudentNo] [NVARCHAR](20) NULL,
- [Age] [INT] NULL,
- [Sex] [NVARCHAR](2) NULL,
- [Description] [NVARCHAR](100) NULL,
- [classID] [INT] NULL
- ) ON [PRIMARY]
3.安裝EntityFramework數據庫
點擊「References」,鼠標右鍵選擇:「Manage NuGet Packages...」。ide
在線搜索「EntityFramework」,下載安裝測試
![](http://static.javashuo.com/static/loading.gif)
4.添加數據庫鏈接字符串ui
雙擊「Web.config」spa
添加鏈接字符串:.net
- <connectionStrings>
- <add name="DataConnection" connectionString="server=127.0.0.1;database=Test;uid=sa;pwd=123456" providerName="System.Data.SqlClient"/>
- </connectionStrings>
![](http://static.javashuo.com/static/loading.gif)
5.在Models目錄下,添加實體上下文類StuInfoDBContextcode
注意添加EF應用server
DataConnection爲鏈接字符串的名稱
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.Entity;
-
- namespace Iweb.Areas.SiteInfo.Models
- {
- public class StuInfoDBContext:DbContext
- {
- public StuInfoDBContext()
- : base("DataConnection")
- {
- }
- }
- }
![](http://static.javashuo.com/static/loading.gif)
6.在Models目錄下,添加實體模型類Student
注意和數據庫中表名保持一致,不然EF會新建立一張實體模型類對應的表
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace Iweb.Areas.SiteInfo.Models
- {
- public class Student
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string StudentNo { get; set; }
- public int Age { get; set; }
- public string Sex { get; set; }
- public string Description { get; set; }
- public int classID { get; set; }
- }
- }
![](http://static.javashuo.com/static/loading.gif)
7.這樣程序就和數據庫鏈接起來了,程序中的實體模型和數據庫中的表一一對應
8.測試
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Data;
- using Iweb.Areas.SiteInfo.Models;
-
- namespace Iweb.Areas.SiteInfo.Controllers
- {
- public class SiteInfoController : Controller
- {
-
-
-
- public ActionResult Index()
- {
- StuInfoDBContext stuContext = new StuInfoDBContext();
- string sql = @"INSERT INTO dbo.Student
- ( Name ,
- StudentNo ,
- Age ,
- Sex ,
- Description ,
- classID
- )
- VALUES ( N'abc' , -- Name - nvarchar(30)
- N'1010322119' , -- StudentNo - nvarchar(20)
- 24 , -- Age - int
- N'男' , -- Sex - nvarchar(2)
- N'健身,登山' , -- Description - nvarchar(100)
- 2 -- classID - int
- )";
- stuContext.Database.ExecuteSqlCommand(sql);
- List<Student> stuLis= stuContext.Database.SqlQuery<Student>("SELECT * FROM dbo.Student").ToList();
- return View();
- }
-
- }
- }
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
原創「http://blog.csdn.net/tkdwave520/article/details/44629903」