EntityFramwork 使用方法總結

來源:互聯網
上載者:User

之前一直在按照書中的步驟使用,感覺上還不是很清晰,今天總結了一下使用方法:

第一步:建立一個控制台項目:

建立實體類Product

class Product
{
public int ProductID { get; set; }

public string Name { get; set; }

public string Description { get; set; }

public string Category { get; set; }

public decimal Price { get; set; }
}

 

建立介面

interface IProduct
{
IQueryable<Product> Products { get; }
}

 

第二步:建立EntityFramework映射到資料庫的類

 

class EFDbContext:DbContext
{
public DbSet<Product> Products { get; set; }
}

 

DbContext引用在System.Data.EntityFramwork中,我用的VS2010版本沒有預設安裝EntityFramwork

需要在 視圖——其他視窗——Package Manager Console 視窗中 輸入以下命令:

 

Installl -Package EntityFramwork

然後VS會自動連網下載EntityFramework並安裝到項目中,我當前使用的版本是 EntityFramework 4.3.1

 

安裝成功以後發現DbContext類已經正常引用。

第三步:實現IProduct介面

class EFRepository:IProduct
{
private EFDbContext context = new EFDbContext();
#region IProduct 成員

public IQueryable<Product> Products
{
get { return context.Products; }
}

#endregion

}

 

第四步:通過設定檔 指定要串連的資料庫檔案

開啟App.config 檔案,添加以下代碼:

<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=I:\程式員的修鍊之道\BrooklynWorkShop\personal\SportStore.sdf;Password=1;Persist Security Info=False;" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

 

至此,所有準備工作就緒

 

測試:在Program.cs檔案中編寫測試代碼:

class Program
{
static void Main(string[] args)
{
EFRepository repository = new EFRepository();

IEnumerable<Product> products = repository.Products.AsEnumerable();

foreach (Product p in products)
{
Console.WriteLine(p.Name);
}

Console.Read();
}
}

 

F5運行,

控制台輸出:

成功!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.