Entity Framework访问数据学习笔记
ADO.NET Entity FrameWork操作数据库的过程对用户是透明的。我们唯一能做的是操作EDM(Entity Data Model),EDM会将这个操作请求发往数据库。
Entity FrameWork实现了一套类似于ADO.NET2.0中连接类的被称作EntityClient的类用来操作EDM。ADO.NET2.0的连接类是向数据库发送SQL命令操作表或视图,而Entity FrameWork是向EDM发送EntitySQl操作Entity。
几种访问数据的操作方法:
1.EntityClient+EntitySQL
这种方式同ADO.NET访问数据库的代码基本一样。
using (EntityConnection conn = new EntityConnection("Name=TestEntities"))
{
int uId = 50;
conn.Open();
EntityCommand cmd = new EntityCommand("SELECT VALUE u FROM TestEntities.T_User AS u WHERE u.U_ID=@uid", conn); cmd.Parameters.AddWithValue("uid", uId);
EntityDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
User user = null;
while (reader.Read())
{
user = new User()
{
U_ID = Int32.Parse(reader["U_ID"].ToString()),
U_UserName = reader["U_UserName"].ToString(),
U_Password = reader["U_Password"].ToString()
};
}
reader.Close();
conn.Close();
return user;
}
2.ObjectService+EntitySQL
using (TestEntities entities = new TestEntities())
{
ObjectQuery<User> query = entities.CreateQuery<User>(
"SELECT VALUE u FROM TestEntities.T_User AS u WHERE u.U_ID=@uid",
new ObjectParameter("uid",uId)
);
return query.ToList()[0];
}
3.ObjectContext+Linq
3.1.
using (TestEntities entities = new TestEntities())
{
int uId = 50;
var user = entities.T_User.Where(u=>u.U_ID==uId);
if (user.ToList().Count > 0)
{
return user.Single();
}
return null;
}
3.2.
using (TestEntities entities = new TestEntities())
{
int uId = 50;
var user = from u in entities.T_User
where u.U_ID == uId
select u;
if (user.ToList().Count > 0)
{
return user.Single();
}
return null;
}