Entity Framework的简单示例
在具有 ASP.NET 的三层结构中使用 Entity Framework 的简单示例
引言
此示例展示了如何在具有分层架构的 ASP.NET 应用程序中使用 Entity Framework。 这对于相当小且快速的应用程序很有用。 该代码使用 select
、update
、create
和 delete
函数。 你可以将此示例与存储过程一起使用,也可以不使用。 此示例面向 EF 的新手。
这是一个小的想法,让我实现在 ASP.NET 中 Entity Framework 的概念,但说实话,我在进行此练习时遇到了很多障碍。 第一个上下文很复杂,这会在内存中创建一些对象,另一方面,我不得不发送要处理的对象。 没有必要将存储的实体框架作为关键,否则会引发错误。
数据库
首先查看数据库的结构。 此示例使用两个表,即 Customers
和 Category
。 Customers
与 Category
具有关系。

项目
该项目具有三层结构。 包含项目实体的业务层、项目组件、数据层和表示层。

业务层包含两个项目 Solution.Bussines.Entities
。 这包含与表相同的结构,并映射到数据库的结构。
模型具有与使用 ADO.NET Entity Data Model 的数据库相同的结构。

customer
表与存储过程有关系。

重要的是,您需要了解 delCustomer
的关系,您只需要 Id
进行删除,但实体框架需要引用的表。
下一个类 Customers
扩展了使用 ADO.NET Entity Data Model 生成的模型,该模型使用 CategoryReference
在以下行中加载 Customer
的 Category
this.CategoryReference.Load();
此表单很容易获得另一个类中引用的类,也可以用于在网格中显示。
public partial class Customers
{
public const string EntitySetName = "Customers";
[Browsable(false)]
public string CategoryName
{
get
{
string res = "";
if (this.Category != null)
{
res = this.Category.Name;
}
else if (this.CategoryReference != null)
{
this.CategoryReference.Load();
if (this.Category != null)
{
res = this.Category.Name;
}
}
return res;
}
set
{
this.CategoryReference.EntityKey =
new EntityKey("CustomersEntities.Category", "CategoryId", value);
}
}
在下一个代码片段中,扩展了类实体或最佳调用上下文,因为它具有单例模式,并且解决了在使用 using
或 dispose
时创建许多未完全关闭的实例的问题。
public static CustomersEntities Context
{
get
{
string objectContextKey = HttpContext.Current.GetHashCode().ToString("x");
if (!HttpContext.Current.Items.Contains(objectContextKey))
{
HttpContext.Current.Items.Add(objectContextKey, new CustomersEntities());
}
return HttpContext.Current.Items[objectContextKey] as CustomersEntities;
}
}
业务层
Solution.Bussines.Components
层管理业务逻辑,并将数据层与实体层连接起来。
此层由类 *CustomersComponent.cs* 组成,该类调用数据层。 在这里,您可以为您的业务添加更多逻辑代码。
/// <summary>
/// Submit an Customers.
/// </summary>
/// <param name="Customers">An Customers object.</param>
public Customers CreateCustomer(Customers customers)
{
Console.WriteLine("Submitting... ");
try
{
customers = CreateCustomers(customers);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
Console.WriteLine("New CustomersID = " + customers.Id.ToString());
return customers;
}
/// <summary>
/// Creates a new Customers record in the database.
/// </summary>
/// <param name="customers">An Customers object.</param>
private Customers CreateCustomers(Customers customers)
{
// Business logic.
Console.WriteLine(customers.ToString());
// Persist data.
CustomersDAC dac = new CustomersDAC();
return dac.Create(customers);
}
按名称列出 customer
,此方法调用数据访问层。
/// <summary>
/// return a list of customers by name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public List<Customers> ListCustomersByName(string name)
{
// Retrieve data.
CustomersDAC dac = new CustomersDAC();
return dac.SelectByName(name);
}
数据层
数据层包含用于访问数据库的逻辑。
在数据库中插入新记录。 此方法使用先前创建的客户添加到上下文,并在数据库中保存更改。
/// <summary>
/// Inserts an Customers row.
/// </summary>
/// <param name="Customers">An Customers object.</param>
public Customers Create(Customers customers)
{
CustomersEntities ctx = CustomersEntities.Context;//)
try
{
ctx.AddToCustomers(customers);
ctx.SaveChanges();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw ex;
}
return customers;
}
更新数据库中的记录。 此方法不会将对象添加到上下文中,因为先前已获得该对象。
/// <summary>
/// Updates an Customers row.
/// </summary>
/// <param name="Customers">A Customers object.</param>
public void Update(Customers Customers)
{
CustomersEntities ctx = CustomersEntities.Context;//)
try
{
ctx.SaveChanges();
}
catch (Exception ex){
Debug.WriteLine(ex.Message);
throw ex;
}
}
上下文包含作为属性的表,以便您可以访问它并获得通用类的列表。
下一个方法选择 customers
表的记录。
/// <summary>
/// Returns a set of Customers that belongs to an employee
/// </summary>
/// <returns>A List of Customers.</returns>
public List<Customers> Select()
{
List<Customers> resultsList = null;
CustomersEntities ctx = CustomersEntities.Context;//)
resultsList = ctx.Customers.ToList();
return resultsList;
}
下一个方法通过 ID 获取客户表的记录。 这使用表达式 lambda 按 Id 过滤。 使用方法 First
,您肯定会获得一条记录。 获取客户记录后,加载引用的表。
public Customers getCustomer(int Id)
{
Customers custre = null;
CustomersEntities ctx = CustomersEntities.Context;
{
custre = ctx.Customers.First(e => e.Id == Id);
}
custre.CategoryReference.Load();
return custre;
}
下一个方法 Delete
记录表 customer
,首先获取记录,然后调用方法 DeleteObject
以临时删除记录。 最后,它调用 Save changes,以确保保存在数据库中。
public void Delete(int Id)
{
CustomersEntities ctx = CustomersEntities.Context;
Customers cust = ctx.Customers.First(c => c.Id == Id);
ctx.DeleteObject(cust);
ctx.SaveChanges();
}
表示层
在 ASP.NET 中构建的表示层中,我们有用于更新或添加记录的表单,主要方法将操作发送到要执行在数据库中的层组件。 首先使用表单信息填充对象 customer
,然后调用 Update 或 Add。
为了更新记录,首先获取上下文的记录。
protected void btnEnviar_Click(object sender, EventArgs e)
{
CustomersComponent custc = new CustomersComponent();
Customers cust = null;
// if id customer for edit
if (Id > 0)
{
cust = custc.getCustomer(Id);
cust.Name = txtName.Text;
Category category = custc.GetCategory(
int.Parse(ddlCategories.SelectedValue));
cust.Category = category;
custc.UpdateCustomer(cust);
}
else
{
// agregar
cust = new Customers();
cust.Name = txtName.Text;
Category category = custc.GetCategory(
int.Parse(ddlCategories.SelectedValue));
cust.Category = category;
custc.CreateCustomer(cust);
}
Response.Redirect("Default.aspx");
}
下一个方法在表单中加载 customer
private void LoadCustomer()
{
CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();
}
请评论并投票支持本文,以便下次改进。
历史
- 2009 年 7 月 9 日:首次发布