Is it possible to make a request using the EF tools without describing the database context, or creating and describing it directly in the function before the request?

  • one
    And why is it necessary, what does not suit the method with the context? - Ildar

2 answers 2

You can create a context and perform a direct query:

public class Client { public int Id { get; set; } public string Name { get; set; } } public class Program { public static void Main() { var context = new DbContext("ConnectionString"); var xxx = context.Database.SqlQuery<Client>("select Id, Name from Clients").ToList(); } } 

It will not have a DBSet 's, but queries can be performed via SqlQuery and ExecuteSqlCommand .
But why use EF if you do not want to use EF?

  • What was required! Thank you very much! - tigrik2017 September

If you do not want to describe the context, then you do not need all the advantages of the template unit of work with the repository implemented by the Entity Framework. It is enough to use the ADO.NET technology (code samples)

  string connectionString = "Data Source=(local);Initial Catalog=Northwind;" + "Integrated Security=true"; // Provide the query string with a parameter placeholder. string queryString = "SELECT ProductID, UnitPrice, ProductName from dbo.products " + "WHERE UnitPrice > @pricePoint " + "ORDER BY UnitPrice DESC;"; // Specify the parameter value. int paramValue = 5; // Create and open the connection in a using block. This // ensures that all resources will be closed and disposed // when the code exits. using (SqlConnection connection = new SqlConnection(connectionString)) { // Create the Command and Parameter objects. SqlCommand command = new SqlCommand(queryString, connection); command.Parameters.AddWithValue("@pricePoint", paramValue); // Open the connection in a try/catch block. // Create and execute the DataReader, writing the result // set to the console window. try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("\t{0}\t{1}\t{2}", reader[0], reader[1], reader[2]); } reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } 

You can also look in the direction of LINQ to SQL

  • Not exactly what I need ... I already have one context, but “on the go” I need to declare the context for another database for a single request (for example, for a synchronization operation once every n days). - tigrik2017 September