Entity Framework 4.1(转)
?
.NET 的實體框架越來越完善了,前幾天看到Entity Framework 4.1已經正式發布了,新添加了一種稱為Code First的開發模式。字面上的意思就是代碼優先;按照微軟對于它的說明就是:Code First聚焦于定義你的model類,這些類可以映射到一個現有的數據庫,或者根據這些類生成數據庫,并且提供了數據注解功能和一個易用的API。
下面將對如何使用這種開發模式做一個簡單的說明:
準備:您需要已經安裝VS2010以及Entity Framework 4.1
1、新建項目或網站
無論是網站,還是項目都可以使用Code First的開發模式。
2、添加類庫引用
EntityFramework
System.Data.Entity
System.ComponentModel.DataAnnotations
3、編寫Model類
如果是網站需要把代碼寫到App_Code文件夾下才能夠被編譯執行。
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用于映射數據表中的字段(字段名、字段類型等)。
如果我們不添加這些映射,則框架會按照慣例進行相關的映射處理,開發者不需要做什么顯示配置。
關于這些屬性可以參考:http://msdn.microsoft.com/en-us/library/dd901590(v=vs.95).aspx
EF4.1中支持的包括如下屬性:
KeyAttribute ?主鍵
StringLengthAttribute ?字符串長度
MaxLengthAttribute 最大長度
ConcurrencyCheckAttribute
RequiredAttribute ?必需
TimestampAttribute 時間戳
ComplexTypeAttribute 復合類型
ColumnAttribute ?映射列:column name, ordinal & data type
TableAttribute 映射表:name 和schema
InversePropertyAttribute
ForeignKeyAttribute 外鍵
DatabaseGeneratedAttribute
NotMappedAttribute 在數據庫中排除
4、創建DbContext
繼承DbContext,為上邊創建的Model添加數據集。
public class ProductContext : DbContext
{
????public DbSet<Category> Categories { get; set; }
????public DbSet<Product> Products { get; set; }
????public DbSet<Supplier> Suppliers { get; set; }
}
這可以理解成一個數據操作類,而且DbContext提供了一些方法很不錯,如Find可以根據主鍵查找數據。
5、添加數據庫連接字符串
<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>
注意這個數據連接的名稱要和繼承自DbContext的類的名稱一致,數據庫ProductContext在SQLServer中尚未創建。
6、編寫數據處理
<%@ 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、添加數據<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、查詢數據<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();
????????}
????}
}
有兩個數據操作,添加數據和查詢數據。
在執行數據操作的時候, 如果數據庫不存在則程序首先創建數據庫,再進行數據操作。默認的情況下,如果數據庫已經存在,則不執行更新數據庫結構的操作。
但是我們有時候更改了Model類,希望能夠同步到數據庫中。
完美的實現方式就是我們改了某個字段或者某個表,數據庫中只更新相應的部分就行了。但是這一想法沒有在這個版本中實現。
微軟提供的是如果發現Model類有變化,則重新創建數據庫。微軟的方法無疑會將我們的測試數據清理掉,還好我們可以在初始化的過程中添加測試數據,這樣每次重新創建數據庫的時候,測試數據就會自動加進去了,算是解決了一些問題。
??
轉載于:https://www.cnblogs.com/quietwalk/archive/2011/07/02/2096302.html
總結
以上是生活随笔為你收集整理的Entity Framework 4.1(转)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构-图
- 下一篇: Jack Dongarra/杰克 多加拉