MVC ef 连接数据库
1.创建数据库
2.创建表
- <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...”。
在线搜索“EntityFramework”,下载安装
4.添加数据库连接字符串
双击“Web.config”
添加连接字符串:
- <connectionStrings>
- <add name="DataConnection" connectionString="server=127.0.0.1;database=Test;uid=sa;pwd=123456" providerName="System.Data.SqlClient"/>
- </connectionStrings>
5.在Models目录下,添加实体上下文类StuInfoDBContext
注意添加EF应用
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")
- {
- }
- }
- }
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; }
- }
- }
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
- {
- //
- // GET: /SiteInfo/SiteInfo/
- 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://blog.csdn.net/tkdwave520/article/details/44629903”