2017-05-30 65 views
0

我看了一些EF教程,但是我不知道几件事情。我目前正在使用ADO与SQL服务器数据库交互的.net测试项目中工作。现在我必须将ADO部分传递给实体框架。 我目前正在使用3层,业务,对象和DataAcess。从ADO到实体框架的ASP/C#

在DA中,我有以下查询来从我的网站更新Employee表。它的工作原理,但我想通过使用Linq将它传递给实体框架。我还有其他一些插入和选择的例子,但是我确信一旦我能够对它进行排序,我就能找到它们。

注意:我已经使用实体框架将我的DataAccess类与数据库连接起来,实体列表对象称为ListEntities。

SqlConnection conn = new SqlConnection(); 
try 
{ 
    SqlCommand comm; 
    string connectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString; 

    conn = new SqlConnection(connectionString); 

    comm = new SqlCommand("UPDATE Employee SET [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected] WHERE [email protected]", conn); 
    comm.Parameters.Add("@Name", 
    System.Data.SqlDbType.VarChar, 70); 
    comm.Parameters["@Name"].Value = User.Name; 

    comm.Parameters.Add("@Lname", 
    System.Data.SqlDbType.VarChar, 70); 
    comm.Parameters["@Lname"].Value = User.Lname; 

    comm.Parameters.Add("@Age", 
    System.Data.SqlDbType.Int); 
    comm.Parameters["@Age"].Value = User.Age; 

    comm.Parameters.Add("@Email", 
    System.Data.SqlDbType.NVarChar, 70); 
    comm.Parameters["@Email"].Value = User.Email; 

    comm.Parameters.Add("@AYear", 
    System.Data.SqlDbType.Int); 
    comm.Parameters["@Year"].Value = User.Year; 

    comm.Parameters.Add("@ColorID", 
    System.Data.SqlDbType.Int); 
    comm.Parameters["@ColorID"].Value = User.ColorID; 

    comm.Parameters.Add("@AvatarID", 
    System.Data.SqlDbType.Int); 
    comm.Parameters["@AvatarID"].Value = User.AvatarID; 

    comm.Parameters.Add("@EmployeeID", 
    System.Data.SqlDbType.Int); 
    comm.Parameters["@EmployeeID"].Value = User.UserID; 

    conn.Open(); 
    comm.ExecuteNonQuery(); 
} 
catch (Exception ex) 
{ 
    throw ex; 
} 
finally 
{ 
    conn.Close(); 
} 
+1

如果你只是要重新抛出它,不要捕捉异常。这样做没有意义。并且绝对不要在发现异常时抛出ex;否则将失去堆栈跟踪。只要“扔”; – mason

+0

FYI你可以单行这些:'comm.Parameters.Add(“@ Name”,System.Data.SqlDbType.VarChar,70).Value = User.Name;'保存集合查找。 –

+0

不是我问过的,但很高兴知道。 –

回答

1

我不确定如果我明白你说的话,但我想你想把你提到的这个纯粹的ADO转换成EntityFramework。我不确定在这个例子中你使用EF的步骤是什么,所以我将列出整个步骤。

1-你需要使用包管理器来安装的EntityFramework软件包(在3层)

2-需要创建例如DataContext的来自的DbContext

3-延伸的上下文创建在DbSet职员,Employee类,其属性

public class DataContext : DbContext 
{ 
    public DbSet<Employee> Employees {get; set;} 
} 

4-最后做一个更新

Employee emp = DataContext.Employees.FirstOrDefault(r=>r.EmployeeID == User.UserID); 
emp.Name = User.Name; 
emp.Age = User.Age; 
... 
DataContext.SaveChanges(); 
+0

“r”是什么意思? –

+1

它被称为lamda表达式,它意味着每个ROW都能让我满足这个条件的行:ROW.EmployeeID == User.UserID,你可以放任何你想要的变量,例如FirstOrDefault(p => p.EmployeeID = = User.UserID) –