.net mvc连接数据库
时间: 2023-05-23 21:00:48 浏览: 199
.net MVC 连接数据本地数据库三种方法总结
你可以使用Entity Framework实现.net mvc连接数据库,其中包含对多种关系数据库的支持。你需要添加一个数据库连接字符串,然后定义一个DataContext,使用LINQ to SQL或者Entity Framework进行操作。以下是一个.NET MVC连接数据库的示例代码:
```csharp
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
public class MyContext : DbContext
{
public MyContext() : base("name=MyContext")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Course { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
```
在Controller中可以像下面这样使用上面创建的DataContext:
```csharp
public class HomeController : Controller
{
private MyContext db = new MyContext();
public ActionResult Index()
{
return View(db.Students.ToList());
}
public ActionResult Details(int id)
{
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
```
阅读全文