Entity Framework支持Database First、Model First和Code Only三种开发模式,各模式的开发流程大相径庭,开发体验完全不一样。我综合考虑。主要适用Database First和Code only,所以总结着两种模式!
一、Database First
工具sql 2008和VS2010
建了一个Text数据表,表内容如下
图一:数据库及表结构
在Visual Studio解决方案的DatabaseFirst项目中,添加一个名为DatabaseFirst.edmx的ADO.NET实体数据模型,如下图所示:
点击“添加”按钮后,进入创建实体数据模型向导的选择模型内容界面,如下图所示:
图四:选择从数据库生成模型
选择“从数据库生成”图标,并点击“下一步”按钮,进入选择数据连接界面,如下图所示:
图五:设置数据连接
指定你的本地数据连接,选择“是,在连接字符串中包括敏感数据”选项,并为实体连接设置名称为“DatabaseFirst”,点击“下一步”按钮,进入选择数据库对象界面,如下图所示:
图六选择数据库对象
可供选择的数据库对象包括表、视图和存储过程。按上图所示设置后,点击“完成”按钮,Visual Studio将自动完成从Database到实体数据模型的生成工作。如下图所示:
图七由数据库生成的实体对象模型
如图生成实体对象模型的时候会生成一个App.config,会有这样一段代码,就是数据库连接的代码,我们可以把他考到web.config中,代码如下图:
<connectionStrings> <add name="TestEntities" connectionString="metadata=res://*/DatabaseFirst.csdl|res://*/DatabaseFirst.ssdl|res://*/DatabaseFirst.msl; provider=System.Data.SqlClient; provider connection string=" data source=ASIAIT-SERVER\SERVER2008R2; initial catalog=Test; persist security info=True; user id=sa; password=123; multipleactiveresultsets=True; App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
然后在web项目中添加List.aspx进行业务的增删改查:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="List.aspx.cs" Inherits="EFTest.List" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .style1 { width: 42px; } .style2 { width: 166px; } .style3 { width: 57px; } </style> </head> <body> <form id="form1" runat="server"> <asp:Label ID="lblError" runat="server" ForeColor="Red" /> <div id="toolbar"> 帐号: <asp:TextBox ID="tbAccount" runat="server" /> <asp:Button ID="btnSearch" runat="server" Text="搜索" /> </div> <asp:ListView ID="lvUsers" runat="server" onitemdeleting="lvUsers_ItemDeleting" onitemediting="lvUsers_ItemEditing" DataKeyNames = "ID" onitemupdating="lvUsers_ItemUpdating"> <LayoutTemplate> <table border="1" width="800"> <thead> <tr> <th>ID</th> <th width="200">姓名</th> <th width="60">性别</th> <th width="60">年龄</th> <th width="60">电话</th> <th width="150">操作</th> </tr> </thead> <tbody> <tr id="itemPlaceholder" runat="server"></tr> </tbody> </table> </LayoutTemplate> <ItemTemplate> <tr> <td><a href='Form.aspx?ID=<%# Eval("ID") %>' target="_blank"><%# Eval("ID") %></a></td> <td><%# Eval("Name") %></td> <td><%# Eval("Sex") %></td> <td><%# Eval("Age") %></td> <td><%# Eval("Phone")%></td> <td> <asp:Button ID="btnEdit" runat="server" Text="修改" CommandName="Edit" CommandArgument='<%#Eval("ID")%>'/> <asp:Button ID="ibtnDelete" runat="server" Text="删除" CommandName="Delete" CommandArgument='<%#Eval("ID")%>' OnClientClick="return confirm('删除的数据不可恢复,确定要执行删除操作吗?');" /> </td> </tr> </ItemTemplate> <EditItemTemplate> <tr> <td><asp:TextBox ID="tbId" runat="server" Text='<%# Bind("ID") %>' /></td> <td><asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'/></td> <td><asp:DropDownList ID="dropSex" runat="server" Height="30px" Width="145px"> <asp:ListItem>男</asp:ListItem> <asp:ListItem>女</asp:ListItem> </asp:DropDownList></td> <td><asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>'/></td> <td><asp:TextBox ID="txtphone" runat="server" Text='<%# Eval("Phone")%>' /></td> <td> <asp:Button ID="tbnEdit" runat="server" Text="保存" CommandName="Update" ValidationGroup="Update" /> <asp:Button ID="tbnCancel" runat="server" Text="取消" CommandName="Cancel" CausesValidation="false" /> </td> </tr> </EditItemTemplate> <EmptyDataTemplate> 没有符合条件的数据 </EmptyDataTemplate> </asp:ListView> <table border="1" width="800"> <tr> <td class="style1">姓名</td> <td class="style2"><asp:TextBox ID="tbName" runat="server" /></td> <td class="style3">性别</td> <td> <asp:DropDownList ID="dropSex" runat="server" Height="30px" Width="145px"> <asp:ListItem>男</asp:ListItem> <asp:ListItem>女</asp:ListItem> </asp:DropDownList> </td> <td></td> </tr> <tr> <td class="style1">年龄</td> <td class="style2"><asp:TextBox ID="tbAge" runat="server" /></td> <td class="style3">电话</td> <td><asp:TextBox ID="tbPhone" runat="server" /></td> <td><asp:Button ID="btnAdd" runat="server" Text="添加" CommandName="Insert" ValidationGroup="Insert" onclick="btnAdd_Click" /></td> </tr> </table> </form> </body> </html>
后代代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseFirst;
using System.Xml.Linq;
namespace EFTest
{
public partial class List : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.lblError.Text = string.Empty;
BindDate();
}
}
/// <summary>
/// 绑定数据
/// </summary>
public void BindDate()
{
var db = new DatabaseFirst.TestEntities();
var list = db.Users.Where(o => "" == "");
this.lvUsers.DataSource = list;
this.lvUsers.DataBind();
}
/// <summary>
/// 添加用户
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnAdd_Click(object sender, EventArgs e)
{
using (var db = new DatabaseFirst.TestEntities())
{
if (db.Users.Count(o => o.Name == tbName.Text) > 0)
{
this.lblError.Text = "姓名已被占用!";
return;
}
var user = new User();
user.Name = tbName.Text;
user.Phone = tbPhone.Text;
user.Sex = dropSex.SelectedValue;
user.Age = Convert.ToInt32(tbAge.Text);
user.RoleId = 1;
db.Users.AddObject(user);
db.SaveChanges();
}
BindDate();
}
/// <summary>
/// 编辑用户
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lvUsers_ItemEditing(object sender, ListViewEditEventArgs e)
{
lvUsers.EditIndex = e.NewEditIndex;
BindDate();
}
/// <summary>
/// 更新数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lvUsers_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
int id = Convert.ToInt32(lvUsers.DataKeys[e.ItemIndex].Value.ToString());
string name = ((TextBox)(lvUsers.Items[e.ItemIndex].FindControl("txtName"))).Text;
string age = ((TextBox)(lvUsers.Items[e.ItemIndex].FindControl("txtAge"))).Text;
string phone = ((TextBox)(lvUsers.Items[e.ItemIndex].FindControl("txtPhone"))).Text;
string sex = ((DropDownList)(lvUsers.Items[e.ItemIndex].FindControl("dropSex"))).SelectedValue;
using (var db = new DatabaseFirst.TestEntities())
{
var user = db.Users.SingleOrDefault(o => o.ID == id);
if (db.Users.Count(o => o.Name == name && o.ID != user.ID) > 0)
{
this.lblError.Text = "姓名已被占用!";
e.Cancel = true;
}
user.ID = id;
user.Name = name;
user.Phone = phone;
user.Sex = sex;
user.Age = Convert.ToInt32(age);
user.RoleId = 1;
db.Users.ApplyCurrentValues(user);
db.SaveChanges();
BindDate();
}
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void lvUsers_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
int id = Convert.ToInt32(lvUsers.DataKeys[e.ItemIndex].Value.ToString());
using (var db = new DatabaseFirst.TestEntities())
{
var user = db.Users.SingleOrDefault(o => o.ID == id);
db.Users.DeleteObject(user);
db.SaveChanges();
BindDate();
}
}
}
}
最后运行效果: