EntityFramework executes SQL statement for parameterized query code example

When we use EntityFramework, in general, we need to add database tables or objects to the edmx file to establish a data mapping model; so as to carry out subsequent additions, deletions, and changes. But sometimes when doing maintenance or renovation of the old system, you will find that there are long assembled SQL statements in the old system code, and many of these connections are very complicated (there can be as many as thousands of lines, for example, now we may use storage The process has been dealt with, but due to the uniform style, customer restrictions, etc.), at this time, we need to clarify the relationship inside, and then add the table to be used in the big edmx, and then use the linq form to query according to the connection relationship. Sometimes it feels really good Wasting time.

        In fact, EntityFramework also supports sql statement query, and the support is also very good; just like using ADO.Net, write a sql statement, the parameters are predefined, and the returned result can be obtained after passing it in. What is more worth noting is that there is no need to pull the data table into the edmx file, just move the SQL statement to be transplanted directly, and pass the parameters in, which can also be said to save time and effort; of course, we have to customize it according to actual needs. Look at the result entity class. Now paste the sample code, consider the time, and directly paste the code in the project, you can refer to and modify it as needed, don't be entangled.

    using (MySQLEntities opxEnity = new MySQLEntities())  
    {  
        var sqlText = "SELECT cpm.ManagerID, usr.Email FROM componentmanagers cpm INNER JOIN users usr ON usr.UserID = cpm.ManagerID INNER JOIN components cmp ON cmp.ComponentID = cpm.ComponentID WHERE usr.Deleted = 0 AND cmp.Deleted = 0 AND cmp.Closed = 0 AND cmp.IsMicros = @IsMicros ORDER BY ManagerID";  
        var args = new DbParameter[] {  
            new MySqlParameter {ParameterName = "IsMicros", Value = 1}  
        };  
        var opsManagers = opxEnity.Database.SqlQuery<OpsManagersModel>(sqlText, args).Distinct(new FastPropertyComparer<OpsManagersModel>("ManagerID")).ToList();  
        //to do ...  
    }  

 Result entity class:

    class OpsManagersModel  
    {  
         public string ManagerID { get; set; }  
         public string Email { get; set; }   
    }  

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326691105&siteId=291194637