OleDbConnection,OracleConnection 或者SqlConnection這種連接,直接執行sql語句。現在的連接方式執行sql語句有了很大的不同,下面先看看簡單的單表的增刪改查操作,然後再看多表的關聯查詢,帶參數查詢等。
一、ADO.NET Entity對單表的增刪改查
有一個表,即在工程中是一個實體user,為了測試方便,所有字段為string型。
1、增加新記錄
增加一條記錄如下:
[csharp]
using (OracleEntities entities = new OracleEntities())
{
User uer = User.CreateUser("id", "name", "age", "1");
entities.User.AddObject(user);
entities.SaveChanges();
using (OracleEntities entities = new OracleEntities())
{
User uer = User.CreateUser("id", "name", "age", "1");
entities.User.AddObject(user);
entities.SaveChanges();
}
2、刪除內容
代碼如下:
using (OracleEntities entities = new OracleEntities())
{
User user = entities.User.First<User>(a => a.ID.Equals("id"));
entities.DeleteObject(user);
entities.SaveChanges();
}
using (OracleEntities entities = new OracleEntities())
{
User user = entities.User.First<User>(a => a.ID.Equals("id"));
entities.DeleteObject(user);
entities.SaveChanges();
}
3、修改內容
代碼如下:
using (OracleEntities entities = new OracleEntities())
{
User user = entities.User.First<User>(a => a.User.Equals("id"));
user.Remarks = "修改了內容";
entities.SaveChanges();
}
using (OracleEntities entities = new OracleEntities())
{
User user = entities.User.First<User>(a => a.User.Equals("id"));
user.Remarks = "修改了內容";
entities.SaveChanges();
}
4、查詢內容
(1)實體直接查詢
[/code]
using (OracleEntities entities = new OracleEntities())
{
ObjectQuery<User> result = entities.User;//查詢所有
foreach (User item in result)
{
}
}
using (OracleEntities entities = new OracleEntities())
{
ObjectQuery<User> result = entities.User;//查詢所有
foreach (User item in result)
{
}
}
[/code]
(2)Esql查詢
代碼如下:
ObjectQuery<DbDataRecord> result = entities.CreateQuery<DbDataRecord>("select value it from OracleEntities.User as it ");
(3)按條件查
代碼如下:
var result = entities.User.Where(o => o.id.Equals("id"));
二、關聯查詢
比如還有個表Other與User外鍵關聯。
進行查詢如下:
代碼如下:
using (OracleEntities entities = new OracleEntities())
{
string esql = "SELECT b.detail FROM OracleEntities.User as a,OracleEntities.Other as b where a.otherid = b.id and a.id='id'";
ObjectQuery<DbDataRecord> query = entities.CreateQuery<DbDataRecord>(esql);
foreach (DbDataRecord r in query)
{
string ss = r["detail"].ToString();
}
}
using (OracleEntities entities = new OracleEntities())
{
string esql = "SELECT b.detail FROM OracleEntities.User as a,OracleEntities.Other as b where a.otherid = b.id and a.id='id'"; www.jb51.net
ObjectQuery<DbDataRecord> query = entities.CreateQuery<DbDataRecord>(esql);
foreach (DbDataRecord r in query)
{
string ss = r["detail"].ToString();
}
}
當然這些都是最基本的用法,因為使用的Linq和ESql,在後面再Linq和ESql的用法裡再詳細說明。