使用MVC .NET中的Entity框架将sql表绑定到View [英] Bind sql table to View using Entity framework in MVC .NET
本文介绍了使用MVC .NET中的Entity框架将sql表绑定到View的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在sql中有一个Student表。我想使用Entity框架数据模型在视图中显示该表的数据。
我对MVC更新。谁能帮我。
谢谢
I have an Student table in sql. I want to show data of this table in view using Entity framework data model.
I am fresher in MVC. Can anyone help me.
Thank you
推荐答案
您好,
尝试使用EF代码首先,理解它会简单得多。
1.创建解决方案(ASP> MVC)
2.在包管理器控制台中下载NuGet包写下一个:
- Install-Package EntityFramework -Version 4.3.1
3)创建数据库上下文类,例如:
Hi,
Try to use EF code first, it would be much simpler to understand it.
1. Create your solution(ASP>MVC )
2. Download NuGet package in package manager console write the next:
- Install-Package EntityFramework -Version 4.3.1
3) Create you database context class, for example:
public calss StudentContext:DbContext
{
public StudentContext():base("name=ConStringName"){}
//where ConStringName -> key of your connection string in config file.
public DbSet<student> Students{get;set;}
}</student>
4)创建学生实体 - >
4) Create Student Entity ->
public class Student
{
[System.ComponentModel.DataAnnotations.Key] //do not forget to add reference to System.ComponentModel.DataAnnotations.dll
public int Id{get;set;}
[Required()]
public string Name {get;set;}
//other stuff was ommited for brevity!!
}
5)创建StudentController模块并在其中实现Index方法:
5) Create StudentController module and implement Index method in it:
public class StudentController:Controller
{
public ActionResult Index()
{
using(var context=new StudentContext())
{
return View(context.Students.AsEnumerable());
}
}
}
6)你最后一个是创建索引查看:
6) the last one all you nedd is to create Index view:
@model IEnumerable<student>
@{
ViewBag.Title="Student index page"
}
<ul>
@{
foreach(var student in Model)
<li>@student.Name</li>
}
</ul>
希望这会对您有所帮助!!
Hope this will help you!!
你可以添加en您的项目中的tity模型(edmx),然后您可以使用该模型将表绑定到视图。
you can add entity model (edmx) in your project and then you can bind the table with view using that model.
这篇关于使用MVC .NET中的Entity框架将sql表绑定到View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文