[英]Get Data from DB With EF
I've recently started working with EF6 So my knowledge on it isn't very great. 我最近开始使用EF6,所以我对它的了解不是很好。 I am currently working on test web project which I have created using VS Express 2013. EF has created the required tables.
我当前正在使用VS Express 2013创建的测试Web项目。EF已创建所需的表。 Now I've added my own table which has basic information such as:
现在,我添加了自己的表,该表具有以下基本信息:
FirstName 名字
Surname 姓
DOB DOB
What I'm trying to gather is would I write a SQL query in my function to get the data from the database so something like 我要收集的是在函数中编写一个SQL查询以从数据库中获取数据,例如
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select * from my table", connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//Read Data
}
}
}
Or is there a separate way to write it in EF? 还是有单独的方法可以在EF中编写它? Because I couldn't find how and where the
SQL syntax
queries are used in EF or maybe I'm just missing something? 因为我找不到在EF中使用
SQL syntax
查询的方式和位置,或者我只是缺少什么? Thanks in advance for your help & support 预先感谢您的帮助和支持
Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects.
实体框架(EF)是一种对象关系映射器,它使.NET开发人员能够使用特定于域的对象来处理关系数据。 It eliminates the need for most of the data-access code that developers usually need to write.
它消除了开发人员通常需要编写的大多数数据访问代码。
You need to review more there http://msdn.microsoft.com/en-gb/data/ef.aspx and at least read some intros to EF or some video tutorials. 您需要在http://msdn.microsoft.com/en-gb/data/ef.aspx上查看更多内容,并且至少阅读EF的一些简介或一些视频教程。
var context = new EntitiesContext();//DbContext Object
var list = ent.Customers; // will return all customers.
The code you have posted is using ADO.Net. 您发布的代码正在使用ADO.Net。 You can perform raw sql in entity framework like this
您可以在这样的实体框架中执行原始sql
Entities ent = new Entities();//DbContext Object
var list = ent.tablename.SqlQuery("select * from my table");
And using Entity framework to get data from db 并使用实体框架从数据库获取数据
Entities ent = new Entities();//DbContext Object
var data = ent.tableName;
The point of EF is that you don't have to write SQL queries. EF的要点是您不必编写SQL查询。 You have an object model you use to access the database:
您具有用于访问数据库的对象模型:
using (var context = new YourEntities())
{
var records = context.Table; // .Where(t => t.Name == "foo")
foreach (var record in records)
{
// ...
}
}
Please check out the Quickstart example from MSDN 请查看MSDN的快速入门示例
http://msdn.microsoft.com/en-us/library/vstudio/bb399182%28v=vs.100%29.aspx http://msdn.microsoft.com/zh-cn/library/vstudio/bb399182%28v=vs.100%29.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.