如何在ASP.NET Web Forms网站中使用Entity Framework 6进行基本CRUD



我正在学习实体框架6。我正在寻找一个教程,解释如何设置ASP.NET Web Forms网站(而不是ASP.NET MVC)和创建基本的CRUD页面。我能找到的唯一教程是基于MVC和/或控制台应用程序,而不是web应用程序。

我熟悉MVC,但我不想在这个项目中使用MVC。仅限实体框架6网络表单。所有教程似乎都是基于MVC的,或者它们会引导您创建控制台应用程序而不是Web应用程序。

我遇到的一个例子是试图在网页中添加一个简单的网格视图。

这似乎应该是一个简单的过程,但我还没有找到使其工作的代码。我想我一定错过了一个简单的步骤。该页面有一个名为Gridview1的网格视图。在我使用的代码后面:

namespace EFTestSchool.Models
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Student db = new Student();
GridView1.DataSource
}
}
}

当我将.Models添加到命名空间时,它表示找不到Gridview1。当我将名称空间简单地用作EFTestSchool时,Gridview1被识别,但我的行Student db=New Student()表示找不到Student。我的项目名称是EFTestSchool。我的模特的名字叫SchoolModel。这是基于一些教程中使用的标准学校数据库。我一定错过了一些非常简单的东西,这些东西使我无法在网页中添加一个简单的网格。

如有任何建议,我们将不胜感激。

我想不出你为什么要选择ASP.NET Web Forms而不是现在更现代的.NET替代方案。但假设你有充分的理由,这就是我的答案。

首先,这里有一个关于实体框架、crud和webforms的教程。实体框架代码现在有点过时了。但是,如果你了解你提到的控制台应用程序演示,你应该能够从中了解如何将其应用于网络表单。

根据你的描述,我认为你对名称空间的工作方式感到困惑。这段代码有望对此有所帮助。

using AnotherNamespace;  //this means the code on the page can access the public 
//parts of AnotherNamespace
namespace MyNamespace
{
//code in here belongs to MyNamespace
}

下面是一个简单的例子,我认为您的代码应该是什么样子。

首先您的dbcontext

using EFTestSchool.Models;
using System.Data.Entity;
namespace EFTestSchool.Data
{
public class MyDbContext: DbContext
{
public DbSet<Student> Students { get; set; }
public MyDbContext()
:base("{your connection string}")
{
Database.SetInitializer<MyDbContext>(null);
}
}
}

学生模型

namespace EFTestSchool.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}

Default.aspx文件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EFTestSchool.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">     
<asp:GridView ID="Gridview1" runat="server">
</asp:GridView>
</form>
</body>
</html>

后面的代码,即default.aspx。cs

using EFTestSchool.Data;
using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using EFTestSchool.Models;  //use this in your code to remove the student cannot be found compiler error
namespace EFTestSchool  //needs to stay as this or it won't be able to recognise the controls in the aspx file
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{            
if(!IsPostBack)
{
using (var ctx = new MyDbContext())
{
var students = ctx.Students.ToList();
Gridview1.DataSource = students;
Gridview1.DataBind();
}
}    
}
}
}

最新更新