asp mvc plain sql possible? - asp.net-mvc

Is there a way to use simple sql queries on ASP MVC without using LINQ thing?
any link is welcome :)

Of course, you can always drop down to use regular ol' ADO.NET :-)
The Data Access Application Block is also commonly used to simplify the execution of raw sql and stored procedures.

Sure, you can embed plain ADO.NET objects within your controller's action methods or in a custom business logic library. A bit of an example. WARNING: DEMONSTRATION CODE ONLY. DO NOT ATTEMPT TO USE IN PRODUCTION SCENARIO.
public ActionResult Index()
{
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CNTax"].ConnectionString))
{
using(SqlCommand command = conn.CreateCommand())
{
command.CommandText = "select * from Names";
command.CommandType = CommandType.Text;
conn.Open();
var table = new DataTable();
table.load(command.ExecuteReader());
return View("Index", table);
}
}
}
A simple code snippet to select all names from the database and return the index view with the model set as a DataTable.

You sure can. And it is done the same way as you normally would in an ASP.NET application just like the other answers here have indicated.
....HOWEVER, I prefer to use a tool to generate my data access layer. Some of the top choices right now are nHibernate, and LLBLGen Pro, or even Microsoft's Entity Framework
I personally would go with nHibernate or LLBLGen Pro, depending on if you want to have your data access layer driven by "domain driven design" (nHibernate) or "data driven design" (LLBLGen Pro)

Building off of #user102220's answer:
Set up a data access layer (just a separate class or series of classes), then call these from your controller. Apply ADO.NET as necessary.

If you are using Entity Framework you can use SqlQuery like this:
using(var db = new DbContext())
{
var result = db.Database.SqlQuery<your object>("Your Query",params));
}
Your object : your expected result Type (object or class Type) and
Your query and params : sql command with params you should pass to query or not

try this solution:
var results = DynamicCall.DynamicListFromSql(_entities, "select * from users", null).ToList();
public static IEnumerable<dynamic> DynamicListFromSql(this DbContext db, string Sql, Dictionary<string, object> Params)
{
using (var cmd = db.Database.Connection.CreateCommand())
{
cmd.CommandText = Sql;
if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); }
using (var dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
var row = new ExpandoObject() as IDictionary<string, object>;
for (var fieldCount = 0; fieldCount < dataReader.FieldCount; fieldCount++)
{
row.Add(dataReader.GetName(fieldCount), dataReader[fieldCount]);
}
yield return row;
}
}
}
}

Related

How to get specific rows in ASP.NET MVC?

I tried to call the database using ADO.NET and with the code I saw here last time...
private DBEntities db = new DBEntities();
public ActionResult ShowPage(int ID)
{
var query = from a in db.Products
where a.ID.Contains(ID)
select a;
var item = query.FirstOrDefault();
if (item != null)
return View(item);
else
return View(db.Products.ToList());
}
I got this code here and changed some of it.
It shows the whole table in the database
I'm new to programming that's why I don't know how to use it.
I'm not sure but I think I use ASP.NET Web Application .NET Framework 4.7.x when I created it.

MVC ADO without using EF

i wonder how to implement M-V-C ADO without using EF.
just like a pure ADO implementation. any suggestions and sample are appreciated Thanks guys.
Basic ADO.NET connections haven't really changed at all with MVC coming around. They still rely on things like SqlConnection objects and their associated commands.
If you wanted to build a simply query, it might look like the following :
// Build your connection
using(var connection = new SqlConnection("{your-connection-string-here"}))
{
// Build your query
var query = "SELECT * FROM YourTable WHERE foo = #bar";
// Create a command to execute your query
using(var command = new SqlCommand(query,connection))
{
// Open the connection
connection.Open();
// Add any parameters if necessary
command.Parameters.AddWithValue("#bar", 42);
// Execute your query here (in this case using a data reader)
using(var reader = command.ExecuteReader())
{
// Iterate through your results
while(reader.Read())
{
// The current reader object will contain each row here, so you
// can access the values as expected
}
}
}
}
You can use the type of ADO commands and paramaterized SQL seen here to retrieve data:
conn.Open();
cmd.CommandText = "SELECT id, desc FROM mytable WHERE id = #id";
cmd.Parameters.AddWithValue("#id", myid);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
return null;
}
return new myItem
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
Desc = reader.GetString(reader.GetOrdinal("desc")),
}
}
There are lot of examples on MSDN for CRUD.

Bulk Inserting Excel Data to Database Using EF Code First

I use asp.net mvc ef code first. I upload the file to the server all i need is inserting that excel data to code first database. What is the best way to bulk insert excel data to database? Would appreciate your consultation.
Thanks in advance.
You can user LinqToExcel to get data from the Excel file and map it in your entity class.
If you are looking for alternative methods, these are some:
OLEDB, see an example
OPEN XML 2.0
Some third party DLL like ExcelDataReader or EPPlus
Using an ORM like Entity Framework is not efficient to perform bulk operations. To bulk insert efficiently, the SqlBulkCopy class must be used.
To insert a generic list it must be converted to a DataTable:
To insert a generic list it must be converted to a DataTable:
public static DataTable ConvertToDataTable<T>(IList<T> list)
{
PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
Type propType = propertyDescriptor.PropertyType;
if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
table.Columns.Add(propertyDescriptor.Name, Nullable.GetUnderlyingType(propType));
}
else
{
table.Columns.Add(propertyDescriptor.Name, propType);
}
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T listItem in list)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(listItem);
}
table.Rows.Add(values);
}
return table;
}
Then the SqlBulkCopy can be used. In the example the user table is bulk inserted:
DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connection))
{
sqlBulkCopy.ColumnMappings.Add("UserID", "UserID");
sqlBulkCopy.ColumnMappings.Add("UserName", "UserName");
sqlBulkCopy.ColumnMappings.Add("Password", "Password");
sqlBulkCopy.DestinationTableName = "User";
sqlBulkCopy.WriteToServer(dt);
}
}

Execute raw SQL query in ASP.NET MVC, database first mode

The model of my project is database first, and uses remote access to database on another server.
I need to use raw SQL query because my query is very complex and I feel more comfortable in SQl not LINQ.
This is how I do:
string query = "select * from Inquiry_TBL where ...";
using (educationEntities db = new educationEntities())
{
var list = db.Database.SqlQuery<Inquiry_TBL>(query);
ViewData["total"] = list.Count();
}
The problem is sometimes I get the query result within a second, sometimes it just keep loading for a long time and gives me an error that 'Calling 'Read' when the data reader is closed is not a valid operation.'
Why is that? Is there something wrong with my code, or because I'm using remote access to another server? Will switching to local server solve the problem?
The Entity Framework Code First API includes methods that enable you to pass SQL commands directly to the database. You have the following options:
• Use the DbSet.SqlQuery method for queries that return entity types. The returned objects must be of the type expected by the DbSet object, and they are automatically tracked by the database context unless you turn tracking off. (See the following section about the AsNoTracking method.)
• Use the Database.SqlQuery method for queries that return types that aren't entities. The returned data isn't tracked by the database context, even if you use this method to retrieve entity types.
• Use the Database.ExecuteSqlCommand for non-query commands.
Calling a Query that Returns Entities:
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Commenting out original code to show how to use a raw SQL query.
//Department department = await db.Departments.FindAsync(id);
// Create and execute raw SQL query.
string query = "SELECT * FROM Department WHERE DepartmentID = #p0";
Department department = await db.Departments.SqlQuery(query, id).SingleOrDefaultAsync();
if (department == null)
{
return HttpNotFound();
}
return View(department);
}
Calling a Query that Returns Other Types of Objects:
public ActionResult About()
{
//Commenting out LINQ to show how to do the same thing in SQL.
//IQueryable<EnrollmentDateGroup> = from student in db.Students
// group student by student.EnrollmentDate into dateGroup
// select new EnrollmentDateGroup()
// {
// EnrollmentDate = dateGroup.Key,
// StudentCount = dateGroup.Count()
// };
// SQL version of the above LINQ code.
string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
+ "FROM Person "
+ "WHERE Discriminator = 'Student' "
+ "GROUP BY EnrollmentDate";
IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);
return View(data.ToList());
}
Calling an Update Query:
[HttpPost]
public ActionResult UpdateCourseCredits(int? credit)
{
if (credit != null)
{
ViewBag.RowsAffected = db.Database.ExecuteSqlCommand(
"UPDATE Course SET Credits = Credits * {0}", credit);
}
return View();
}
For more information have a look at Advanced Entity Framework 6 Scenarios for an MVC 5 Web Application (12 of 12).

Can we return a multiple result set in stored procedure and how to handle it in .net

Can we return a multiple result set in stored procedure and how to handle it in .net
???
if yes how??
if no why not ??
please explain
If you are retrieving data using DataReader, you can use NextResult method to iterate through multiple resultsets returned by stored procedure. More information can be found here.
The following code is a simple example from MSDN:
static void RetrieveMultipleResults(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM dbo.Categories;" +
"SELECT EmployeeID, LastName FROM dbo.Employees",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.HasRows)
{
Console.WriteLine("\t{0}\t{1}", reader.GetName(0),
reader.GetName(1));
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
reader.NextResult();
}
}
}
If you are populating a Dataset from a DataAdapter, note that if DataAdapter encounters multiple resultsets, it will create multiple DataTables (one for each resultset) and will add them to the resulting DataSet.
http://msdn.microsoft.com/en-us/library/yf1a7f4f.aspx has some good examples.
you need to change your connectionString to support it. MultipleActiveResultSets=True
http://msdn.microsoft.com/en-us/library/h32h3abf.aspx for config settings;

Resources