Entity Framework 4.1(转)
?
.NET 的實(shí)體框架越來越完善了,前幾天看到Entity Framework 4.1已經(jīng)正式發(fā)布了,新添加了一種稱為Code First的開發(fā)模式。字面上的意思就是代碼優(yōu)先;按照微軟對(duì)于它的說明就是:Code First聚焦于定義你的model類,這些類可以映射到一個(gè)現(xiàn)有的數(shù)據(jù)庫(kù),或者根據(jù)這些類生成數(shù)據(jù)庫(kù),并且提供了數(shù)據(jù)注解功能和一個(gè)易用的API。
下面將對(duì)如何使用這種開發(fā)模式做一個(gè)簡(jiǎn)單的說明:
準(zhǔn)備:您需要已經(jīng)安裝VS2010以及Entity Framework 4.1
1、新建項(xiàng)目或網(wǎng)站
無論是網(wǎng)站,還是項(xiàng)目都可以使用Code First的開發(fā)模式。
2、添加類庫(kù)引用
EntityFramework
System.Data.Entity
System.ComponentModel.DataAnnotations
3、編寫Model類
如果是網(wǎng)站需要把代碼寫到App_Code文件夾下才能夠被編譯執(zhí)行。
public class Category
{
????[StringLength(50)]
????[Column(TypeName = "varchar")]
????public string CategoryId { get; set; }
?
????[StringLength(20)]
????[Column("CategoryName", TypeName = "nvarchar")]
????public string Name { get; set; }
?
????public virtual ICollection<Product> Products { get; set; }
}
?
public class Product
{
????[Key]
????public int ProductId { get; set; }
?
????[StringLength(100)]
????[Column("ProductName", TypeName = "nvarchar")]
????public string Name { get; set; }
?
????[StringLength(50)]
????public string CategoryId { get; set; }
?
????public virtual Category Category { get; set; }
}
?
public class Supplier
{
????[Key]
????[StringLength(36)]
????public string SupplierCode { get; set; }
?
????[StringLength(100)]
????[Column("SupplierName", TypeName = "nvarchar")]
????public string Name { get; set; }
?
????public DateTime AddTime { get; set; }
}
這些Model類和我們平常用的沒什么兩樣,不需要任何基類,只不過增加了一些屬性注解來做持久化映射。
這些屬性定義在System.ComponentModel.DataAnnotations中,比如:Column用于映射數(shù)據(jù)表中的字段(字段名、字段類型等)。
如果我們不添加這些映射,則框架會(huì)按照慣例進(jìn)行相關(guān)的映射處理,開發(fā)者不需要做什么顯示配置。
關(guān)于這些屬性可以參考:http://msdn.microsoft.com/en-us/library/dd901590(v=vs.95).aspx
EF4.1中支持的包括如下屬性:
KeyAttribute ?主鍵
StringLengthAttribute ?字符串長(zhǎng)度
MaxLengthAttribute 最大長(zhǎng)度
ConcurrencyCheckAttribute
RequiredAttribute ?必需
TimestampAttribute 時(shí)間戳
ComplexTypeAttribute 復(fù)合類型
ColumnAttribute ?映射列:column name, ordinal & data type
TableAttribute 映射表:name 和schema
InversePropertyAttribute
ForeignKeyAttribute 外鍵
DatabaseGeneratedAttribute
NotMappedAttribute 在數(shù)據(jù)庫(kù)中排除
4、創(chuàng)建DbContext
繼承DbContext,為上邊創(chuàng)建的Model添加數(shù)據(jù)集。
public class ProductContext : DbContext
{
????public DbSet<Category> Categories { get; set; }
????public DbSet<Product> Products { get; set; }
????public DbSet<Supplier> Suppliers { get; set; }
}
這可以理解成一個(gè)數(shù)據(jù)操作類,而且DbContext提供了一些方法很不錯(cuò),如Find可以根據(jù)主鍵查找數(shù)據(jù)。
5、添加數(shù)據(jù)庫(kù)連接字符串
<connectionStrings>
????????<add
??????????name="ProductContext"
??????????providerName="System.Data.SqlClient"
??????????connectionString="Server=192.168.100.100;Database=ProductContext;User ID=sa;Password=sa;Trusted_Connection=False;Persist Security Info=True "/>
????</connectionStrings>
注意這個(gè)數(shù)據(jù)連接的名稱要和繼承自DbContext的類的名稱一致,數(shù)據(jù)庫(kù)ProductContext在SQLServer中尚未創(chuàng)建。
6、編寫數(shù)據(jù)處理
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
?
<!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>
</head>
<body>
????<form id="form1" runat="server">
????<div>
????????1、添加數(shù)據(jù)<br />
????????Category Name:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
????????<br />
????????<br />
????????<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="添 加"/>
????????<br />
????????<br />
?????????2、查詢數(shù)據(jù)<br />
????????<br />
????????<asp:Button ID="Button2" runat="server" Text="查 詢" OnClick="Button2_Click"/>
????????<br />
????????<asp:Repeater ID="Repeater1" runat="server">
????????????<ItemTemplate>
????????????????<%# eval_r("CategoryId") %> <%# eval_r("Name") %><br />
????????????</ItemTemplate>
????????</asp:Repeater>
????</div>
????</form>
</body>
</html>
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using System.Collections;
?
public partial class _Default : System.Web.UI.Page
{
????protected void Page_Load(object sender, EventArgs e)
????{
?
????}
?
????protected void Button1_Click(object sender, EventArgs e)
????{
????????using (ProductContext db = new ProductContext())
????????{
????????????Category c = new Category()
????????????{
????????????????CategoryId = Guid.NewGuid().ToString(),
????????????????Name = TextBox1.Text
????????????};
?
????????????db.Categories.Add(c);
????????????db.SaveChanges();
????????}
????}
?
????protected void Button2_Click(object sender, EventArgs e)
????{
????????using (ProductContext db = new ProductContext())
????????{
????????????IQueryable<Category> rs = from c in db.Categories
??????????????????????????????????????select c;
?
????????????Repeater1.DataSource = rs.ToList();
????????????Repeater1.DataBind();
????????}
????}
}
有兩個(gè)數(shù)據(jù)操作,添加數(shù)據(jù)和查詢數(shù)據(jù)。
在執(zhí)行數(shù)據(jù)操作的時(shí)候, 如果數(shù)據(jù)庫(kù)不存在則程序首先創(chuàng)建數(shù)據(jù)庫(kù),再進(jìn)行數(shù)據(jù)操作。默認(rèn)的情況下,如果數(shù)據(jù)庫(kù)已經(jīng)存在,則不執(zhí)行更新數(shù)據(jù)庫(kù)結(jié)構(gòu)的操作。
但是我們有時(shí)候更改了Model類,希望能夠同步到數(shù)據(jù)庫(kù)中。
完美的實(shí)現(xiàn)方式就是我們改了某個(gè)字段或者某個(gè)表,數(shù)據(jù)庫(kù)中只更新相應(yīng)的部分就行了。但是這一想法沒有在這個(gè)版本中實(shí)現(xiàn)。
微軟提供的是如果發(fā)現(xiàn)Model類有變化,則重新創(chuàng)建數(shù)據(jù)庫(kù)。微軟的方法無疑會(huì)將我們的測(cè)試數(shù)據(jù)清理掉,還好我們可以在初始化的過程中添加測(cè)試數(shù)據(jù),這樣每次重新創(chuàng)建數(shù)據(jù)庫(kù)的時(shí)候,測(cè)試數(shù)據(jù)就會(huì)自動(dòng)加進(jìn)去了,算是解決了一些問題。
??
轉(zhuǎn)載于:https://www.cnblogs.com/quietwalk/archive/2011/07/02/2096302.html
總結(jié)
以上是生活随笔為你收集整理的Entity Framework 4.1(转)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构-图
- 下一篇: Jack Dongarra/杰克 多加拉