It don't get any data from DataReader - c#

i work with N tiers tec in C# for ado, trying to make it easy to use and capable to change any database kind with out write all the cod all over again ,
my code here doesn't get any error but it doesn't get any values to my textbox
(i am trying to get data from table to many textboxs to update it later)
and here how code works:{
at first i make some functions to take any set any kind of parameters or set any command and then i make other function to to execute what ever i set or get from database all that Function i build it in folder name (Data Access Layer)
then i made other folder (Data Build layer)to take use all those function for what ever i want to do in any page (insert , update , delete , Select),
the last think i do it to call the function i made at at (Data Build layer) to my page or control ,
i do all that because if i Change the database Type ,i change only one class and other classes still the same
i hope i explain enough (sorry for my English not good enough)}
Code :
Class DataAccessLayer
public static void Setcommand (SqlCommand cmd,CommandType type,string commandtext)
{
cmd.CommandType=type;
cmd.CommandText=commandtext;
}
public static void AddSQLparameter(SqlCommand cmd, int size,SqlDbType type,object value,string paramName,ParameterDirection direction)
{
if (cmd == null)
{
throw (new ArgumentException("cmd"));
}
if (paramName == null)
{
throw (new ArgumentException("paramName"));
}
SqlParameter param=new SqlParameter();
param.ParameterName= paramName;
param.SqlDbType=type;
param.Size=size;
param.Value=value;
param.Direction=direction;
cmd.Parameters.Add(param);
}
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close();
return dr ;
}
Class DatabuildLayer
SqlCommand com;
public DatabuildLayer()
{
com = new SqlCommand();
//
// TODO: Add constructor logic here
//
}
public SqlDataReader SelectCatalog(int catid)
{
DataAccessLayer.Setcommand(com, CommandType.Text, "select catname,catdescription,photo from category where catid=#catid" );
DataAccessLayer.addSQLparameter(com,16,SqlDbType.Int,catid,"#catid",ParameterDirection.Input);
return DataAccessLayer.ExecuteSelectCommand(com);;
}
and here my last code that retrieve my data to some textbox
in my Pageload :
protected void Page_Load(object sender, EventArgs e)
{
DatabuildLayer= new DatabuildLayer();
SqlDataReader dr ;
dr = obj.SelectCatalog(catselectddl.SelectedIndex);
if (dr.Read())
{
catnametxt.Text = dr["catname"].ToString();
catdestxt.Text = dr["catdescription"].ToString();
}
}

Is it possible that the query is returning nothing, and dr.Read() is returning false? Assuming the code actually executes (it is hard to tell from here) that is probably the only thing that would stop it working - either that or empty columns.
For what it is worth I think that your code needs to be tidied up a bit from a structural and conventions point of view. You should probably look through your code and consider the naming guidelines for the .NET framework. When others read your code they will want it formatted and consistent with this documentation. http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx
Further, most people doing ASP.NET these days try to look for some way to inject external dependencies (such as databases) into their code using a framework like WebFormsMVP available at
http://webformsmvp.com/ in conjunction with an IoC container like autofac available at http://code.google.com/p/autofac/.
Using this approach you can push all external dependencies out of your application behind interfaces which would make it fairly trivial to plug in a different database engine.

Your current wrapper code is not doing anything particularly useful (just subsituting the existing methods or your own tht do the same thing), and it is not closing the connections correctly. It is... a bit of a mess.
If you aren't already massively familiar with the raw ADO.NET interfaces, then maybe consider something like "dapper" which will do all this for you, with a sane API:
short catid = 16;
using(var conn = GetOpenConnection()) {
var row = conn.Query(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();
if(row != null) {
string name = row.catname, desc = row.catdescription;
// ...
}
}
Or if you have a class with CatName / CatDescription properties:
var obj = conn.Query<Catalogue>(
"select catname,catdescription,photo from category where catid=#catid",
new { catid }).FirstOrDefault();

from my experience, when you close a connection associated with a DataReader, nothing can be retrieved from the reader anymore.
//You closed the connection before returning the dr in the your method below:
public static SqlDataReader ExecuteSelectCommand(SqlCommand cmd)
{
if (cmd == null)
{
throw (new ArgumentNullException("cmd"));
}
SqlConnection con = new SqlConnection();
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
con.Close(); //here your connection was already closed
return dr ; //this dr is disconnected
}

Related

Use Sql connection in a separate file in Azure Function

I am using Azure function to connect to Sql database and retrieve values. I am able to install the necessary Nuget packages and perform Sql connection and querying in the Run() function
I wish to keep this database access function alone in a separate file, and return value to the main function(Run() in this case). But when i create a new class in the Azure function project and write SQL connection code, no "using" statements can be used or installed packages can be used.
I am new to Azure functions and may be i am wrong in this approach. Can you help me out? Thanks.
.
You just need to wrap your code in a method. Here's a sample:
public class SqlQuery
{
private string cs = Environment.GetEnvironmentVariable("SqlConnectionString");
public void Query()
{
using(var conn = new SqlConnection(cs))
{
conn.Open();
var cmd = conn.CreateCommand("SELECT * FROM Table");
var dr = cmd.ExecuteReader();
if(dr == null) return;
while(dr.Read())
{
}
}
}
}
the screenshot you shared contains a class and has started implementation inside the class, whereas you should be creating at least one method inside your class and then add your code into the method which returns the data you expect.
try that it should work!
public class SqlQuery{
public void ExecuteReader()
{
private string cs =Environment.GetEnvironmentVariable("SqlConnectionString");
using(var conn = new SqlConnection(cs))
{
conn.Open();
var cmd = conn.CreateCommand("SELECT * FROM Table");
var dr = cmd.ExecuteReader();
if(dr == null) return;
while(dr.Read())
{
}
}
}}

Update if disabled = 0 in C#

I am making a project in C#- in which one can "vote".
When you run the program you first log in. After you've logged in you have to select a value out of a dropdownlist. After you've selected the teacher you press on a button which votes.
The problem is I don't really know how to let this validate properly. And to check if the person has already voted.
It has to check the column in the database named "disabled" if the value = 1 or 0. If the value = 1 they can't vote and if it's 0 they can.
When the person votes it increases the column aantalStemmen by 1. and the disabled column to 1 aswell. Which gets shown in a datagridview.
And the values in the dropdownlist has to match the 1 in the database.
I have this code:
private void db_connection()
{
try
{
conn = "Data Source=localhost;Initial Catalog=docent;Integrated Security=True";
connect = new SqlConnection(conn);
connect.Open();
}
catch (SqlException e)
{
throw;
}
}
private bool validate_disabled(string favoriet)
{
db_connection();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select disabled from leerling";
cmd.Connection = connect;
SqlDataReader disabled = cmd.ExecuteReader();
if (disabled.Read())
{
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void btnStem_Click(object sender, EventArgs e)
{
string favoriet = cmbFavoriete.Text;
db_connection();
SqlCommand cmd = new SqlCommand();
bool r = validate_disabled(favoriet);
if(r){
cmd.CommandText = "UPDATE docent SET aantalStemmen = aantalStemmen + 1 where docentid=#id";
cmd.Parameters.AddWithValue("#id", cmbFavoriete.Text);
}
else
{
MessageBox.Show("You have already voted.");
}
}
my tables in my database looks like this:
Thanks in advance, I've been struggling really hard with this as I'm still a rookie in C#.
I will try an answer to cover more aspects of your code (many already mentioned in comments):
1) Declare your connection string outside of your methods. Also choose meaningful variable names - you will than yourself in a few months when you revisit the code.
private const String ConnectionStr = "Data Source=localhost;Initial Catalog=docent;Integrated Security=True";
2. Appropriate names for methods - also, try to use Camel or Pascal case for method names.
3. Pay attention to possible exceptions. SQLException is not the only possible exception when constructing or opening an SqlConnection, so it is better to catch anything that might occur
private SqlConnection createConnection
{
try
{
connect = new SqlConnection(ConnectionStr);
connect.Open();
}
// this is laziness, but it is better than before
catch (Exception e)
{
// best to log the real error somewhere
throw;
}
}
4. Dispose connection and other disposables like SqlCommand. Also var might save some typing (just hover your mouse over the keyword and you will see the actual type).
SqlConnection allows to directly create a command to be executed using that particular connection by using CreateCommand.
Since your are expecting a single value (scalar) (or a single row with a single column), you can use ExecuteScalar method. So, no more reader.
private bool isDisabled(string favoriet)
{
using (var connection = createConnection())
{
using (var cmd = new connection.CreateCommand())
{
cmd.CommandText = "Select disabled from leerling where leerlingnummer = #number";
cmd.Parameters.AddWithValue("#number", favoriet);
// for simplicity I have assumed that it will always find a value. This should be checked
var disabled = Convert.ToBoolean(cmd.ExecuteScalar());
return disabled;
}
}
}
5. Try not to mix UI logic with database logic (they are usually put in different assemblies)
private void castVote(String favoriete)
{
using (var connection = createConnection())
{
using (var cmd = new connection.CreateCommand())
{
cmd.CommandText = "UPDATE docent SET aantalStemmen = aantalStemmen + 1 where docentid = #id";
cmd.Parameters.AddWithValue("#id", cmbFavoriete.Text);
// command must be actually executed, otherwise nothing happens
cmd.ExecuteNonQuery();
}
}
}
private void btnStem_Click(object sender, EventArgs e)
{
string favoriet = cmbFavoriete.Text;
bool r = isDisabled(favoriet);
if (r)
castVote(favoriet);
// maybe, it would make sense to also notify the user that the vote has been cast
else
MessageBox.Show("You have already voted.");
}
6. Use EntityFramework - in order to avoid the troubles related to handling commands and readers, you can use an ORM to do the dirty work for you.
I would suggest you use bit Data Type (0 - false, 1 - true) instead of int Data Type in your table. It does exactly what you need and you don't have to use int for this.
This means you could change your validate_disabled method to use something like this:
cmd.CommandText = "SELECT disabled FROM leerling WHERE disabled = 1 AND leerlingnummer = #favoriet";
cmd.Parameters.AddWithValue("#favoriet", favoriet);
I've assumed string favoriet is equal to leerlingnummer in your table. After you've executed that query, you would simply check if the query contains more than 0 records - if more than 0 records that means the person does not have permission to vote.

SqlDataReader vs DataSet

I am attempting to get the information of user whenever user logged in to the website, it success when I used a DataSet, but if I want to use the SqlDataReader, the error says: Invalid attempt to read when reader is closed. I have search why is it like that and I have found an article says that
SqlDataReader requires connection remains open in order to get the
data from the server, while DataSet does not need requires
connection remains open.
My question is: I want to know how can I use SqlDataReader as well? So that I don't have to depends on DataSet all the times when I want to get the data from the database.
My problem is occurs when I am trying to change the structure of reading the data function using SqlDataReader, so that it can be re-usable anytime.
Here is the code:
DatabaseManager class:
public SqlDataReader GetInformationDataReader(string procName, SqlParameter[] parameters)
{
SqlDataReader reader = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(procName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach(SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
reader = cmd.ExecuteReader();
}
}
return reader;
}
Web Manager class:
public ModelContexts.InformationContext GetInformation(string username)
{
SqlDataReader reader = null;
ModelContexts.InformationContext context = new ModelContexts.InformationContext();
SqlParameter[] parameters =
{
new SqlParameter("#Username", SqlDbType.NVarChar, 50)
};
parameters[0].Value = username;
try
{
reader = DatabaseManager.Instance.GetInformationDataReader("GetInformation", parameters);
while(reader.Read())
{
context.FirstName = reader["FirstName"].ToString();
context.LastName = reader["LastName"].ToString();
context.Email = reader["Email"].ToString();
}
}
catch(Exception ex)
{
throw new ArgumentException(ex.Message);
}
return context;
}
Controller:
public ActionResult MainMenu(ModelContexts.InformationContext context, string firstName, string lastName, string username, string email)
{
context = WebManager.Instance.GetInformation(User.Identity.Name);
firstName = context.FirstName;
lastName = context.LastName;
username = User.Identity.Name;
email = context.Email;
return View(context);
}
Model contains string return value with getter and setter (FirstName, LastName and Email).
View contains the html label and encode for FirstName, LastName and Email from the Model.
Appreciate your answer.
Thanks.
Here is an approach you can use to keep the code pretty clean that allows you to read from the SqlDataReader while the connection is still open. It takes advantage of passing delegates. Hopefully the code is understandable. You can adjust it to fit your specific needs, but hopefully it illustrates another option at your disposal.
public void GetInformationDataReader(string procName, SqlParameter[] parameters, Action<SqlDataReader> processRow)
{
SqlDataReader reader = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(procName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null)
{
foreach(SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
}
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
// call delegate here.
processRow(dataReader);
}
}
}
}
return reader;
}
public ModelContexts.InformationContext GetInformation(string username)
{
SqlDataReader reader = null;
ModelContexts.InformationContext context = new ModelContexts.InformationContext();
SqlParameter[] parameters =
{
new SqlParameter("#Username", SqlDbType.NVarChar, 50)
};
parameters[0].Value = username;
try
{
// Instead of returning a reader, pass in a delegate that will perform the work
// on the data reader at the right time, and while the connection is still open.
DatabaseManager.Instance.GetInformationDataReader(
"GetInformation",
parameters,
reader => {
context.FirstName = reader["FirstName"].ToString();
context.LastName = reader["LastName"].ToString();
context.Email = reader["Email"].ToString();
});
}
catch(Exception ex)
{
throw new ArgumentException(ex.Message);
}
return context;
}
Brief explanation:
You'll notice that the overall structure of the code is very similar to what you already have. The only changes are:
Instead of returning a SqlDataReader, the GetInformationDataReader() method accepts an Action<SqlDataReader> delegate.
Within the GetInformationDataReader() method, the delegate is invoked at the correct time, while the connection is still open.
The call to GetInformationDataReader() is modified to pass in a block of code as a delegate.
This sort of pattern can be useful for exactly these cases. It makes the code reusable, it keeps it pretty clean and separate, and it doesn't prevent you from benefiting from the using construct to avoid resource/connection leaks.
You have wrapped your SqlConnection object in a using clause, therefore at the end of it SqlConnect.Dispose is called, closing the connection. Whatever caller is consuming your SqlDataReader no longer has the open connection, therefore you're getting your error.
while DataSet does not need requires connection remains open.
That is not entirely correct. DataSet is just an object that is typically filled when called by SqlDataAdapter (the Fill() method of that class). The SqlDataAdapter handles the opening and closing of the SqlConnection, which is most likely why that comment states that. But it's a different class that handles that, not the DataSet itself. Think of the DataSet as just the object that holds the result set of the SqlCommand.
To answer your comment...
So, shouldn't I use using keyword for this matter? In all of the Sql keyword?
I wouldn't take that approach either. You could have a connection leak bug quite easily with that model, and running out of pooled connections could be a not-so-fun thing to troubleshoot.
Typically it's best to consume your data and then close/dispose your connection. There's a saying, "open late, close early". That's typically how you'd want to approach this. I wouldn't try to pass a SqlDataReader object between class methods for this very issue that you're dealing with. The workaround (leaving the connection open) is very error prone.
Another though process, going back to something we mentioned, don't use the SqlDataReader. You have no benefit to cyclically loop through reading each row. Depending on your result set, just fill a DataSet (or usually more appropriate, a DataTable) and return either that Data[Set | Table] or, even better, an object that is more representative of the data it pertains to.

How to create database table class

I have a project in c# about a hospital system which contains 30 child forms.
I have created database which contain more than 30 tables.
I created data access like this:
namespace emamTree
{
public class DBAccess
{
public static string connectionString = ConfigurationManager.ConnectionStrings["TreeFinal"].ConnectionString ;
public SqlCommand Intialize(string query, params SqlParameter[] prmArray)
{
SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, cn);
if (!query.Contains(" "))
cmd.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
cmd.Parameters.AddRange(prmArray);
cn.Open();
return cmd;
}
public int ExcuteNonQuery(string query, params SqlParameter[] prmArray)
{
try
{
SqlCommand cmd = Intialize(query, prmArray);
int affectedRows = cmd.ExecuteNonQuery();
cmd.Connection.Close();
return affectedRows;
}
catch (SqlException ex)
{
return ex.Number;
}
}
public object ExcuteScalar(string query, params SqlParameter[] prmArray)
{
try
{
SqlCommand cmd = Intialize(query, prmArray);
object value = cmd.ExecuteScalar();
cmd.Connection.Close();
return value;
}
catch (SqlException ex)
{
return ex.Number;
}
}
public SqlDataReader ExcuteReader(string query, params SqlParameter[] prmArray)
{
SqlCommand cmd = Intialize(query, prmArray);
SqlDataReader sqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return sqlDataReader;
}
public DataTable ExcuteDataTable(string query, params SqlParameter[] prmArray)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connectionString);
if (!query.Contains(" "))
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
sqlDataAdapter.SelectCommand.Parameters.AddRange(prmArray);
DataTable dt = new DataTable();
sqlDataAdapter.Fill(dt);
return dt;
}
public DataSet ExcuteDataSet(string query, params SqlParameter[] prmArray)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, connectionString);
if (!query.Contains(" "))
sqlDataAdapter.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
if (prmArray.Length > 0)
sqlDataAdapter.SelectCommand.Parameters.AddRange(prmArray);
DataSet ds = new DataSet();
sqlDataAdapter.Fill(ds);
return ds;
}
}
}
In form patient(Table Patient) I create save method and works fine:
public void Save()
{
DBAccess db = new DBAccess();
db.ExcuteNonQuery("insert into Patients (FileNum,PatientTypeID,EngName,NationalityID,RelegionID) values (#FileNum,#PatientTypeID,#EngName,#NationalityID,#RelegionID)",
new SqlParameter("#FileNum", txtFileNum.Text),
new SqlParameter("#PatientTypeID", txtPatientTypeID.Text),
new SqlParameter("#EngName", txtEngName.Text),
new SqlParameter("#NationalityID", txtNationalityID.Text),
new SqlParameter("#RelegionID", txtRelegionID.Text)
);
}
My question is how to make classes for each table in the database?
Use existing solutions like EntityFramework. It provided all the functionality you need and it will make your life much easier than writing it all yourself (and I know, I have done it).
Creating a data access layer is a very critical part of any application. It has to be a separate library so that you can use it in any project today and in the future. Say, tomorrow you want your windows app to be converted to a web application! You can add the DAL libray and start using it.
Having said that, building your own DAL is time cosuming and its like reinventing the wheel. So you need to explore available options which might suite your requirements. Out of the box you have an ORM called EntityFramework. Its pretty straight forward to use but performace wise, its slow compared to handwritten sql. There is also another popular ORM called NHibernate. Its original counterpart Hibernate is huge in java community but it has a very steep learning curve.
But i like to use PetaPoco. It gives best of both worlds. ORM + sql. There are also other such micro ORMs like Dapper, Massive, etc. You need try each one of them and pick the one that suits your application at hand.
Even after choosing a framework that fits your bill, you need to create abstractions to make sure you can change frameworks later if required. Creating a proper DAL is a huge undertaking and has taken big chunk of my time as a developer to get things right. You can explore and find it out by your self. Good luck.

InvalidOpearationException: There is already an open DataReader

Hello I create controls from SQL via this code:
string query = "SELECT * FROM [schema] WHERE idSch=#id";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.AddWithValue("#id", result);
con.Open();
SqlDataReader read= com.ExecuteReader();
while (read.Read())
{
createLabelCmd((int)read["x"], (int)read["y"]);
}
con.Close();
The issue is that createLabelCmd contains SqlCommand and it needs an open SqlConnection
Inside createLabelCmd
String ResultSitting
private void createLabelCmd(int x, int y)
{
for (int i = 0; i < 1; i++)
{
var newLabel = new Label();
newLabel.Location = new Point(x, y);
newLabel.Text = realpocsed.ToString();
string sitting = newLabel.Name;
string sittingSearch = (sitting).Substring(3, 1);
if (sittingSearch != null && kzajezdu == "kZajezdu")
{
string querySitting = "SELECT name, surname FROM klient WHERE sitting = #sitting AND event=#event AND year=#year";
SqlCommand cmdSitting = new SqlCommand(querySitting, spojeni);
cmdSitting.Parameters.AddWithValue("#sitting", sittingSearch);
cmdSitting.Parameters.AddWithValue("#event", idEvent);
cmdSitting.Parameters.AddWithValue("#year", klientClass.Year());
ResultSitting = cmdSitting.ExecuteScalar().ToString().Trim(); //This might be the issue
}
if (kzajezdu == "kZajezdu")
{
newLabel.MouseHover += delegate(object sender, EventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
if (sittingSearch != null)
{
ToolTip1.Show(ResultSitting, newLabel);
}
else { ToolTip1.Show("This sitting is Empty!", newLabel); }
};
}
panel1.Controls.Add(newLabel);
}
I get an Exception: InvalidOpearationException: There is already an open DataReader associated with this Command which must be closed first.
May you please help me solve this out?
Edit as Soner Gönül suggested:
try
{
string query = "SELECT * FROM [schema] WHERE idSch=#id";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.AddWithValue("#id", idSch);
con.Open();
SqlDataReader read= com.ExecuteReader();
while (precti.Read())
{
createLabelCmd((int)read["x"], (int)read["y"]);
}
con.Close();
}
The cause of the problem is outlined in other answers (while a DataReader is open, the connection used by that reader cannot serve other commands), however many fails to talk about MultipleActiveResultSets that has been introduced for this kind of situations
Just change your connection string to include this option and your code will work without any change
Server=yourServer;Database=yourDB;Trusted_Connection=True;MultipleActiveResultSets=true;
To complete the answer, MARS is available starting from SQL Server 2005 and there are minor problems that you should be aware of.
Because when you while loop with your open SqlDataReader, there is an open connection already.
From DataReaders (ADO.NET)
“You can use the ADO.NET DataReader to retrieve a read-only,
forward-only stream of data from a database.
Results are returned as the query executes, and are stored in the
network buffer on the client until you request them using the Read
method of the DataReader”
As a general recomendation, use using like;
using(SqlDataReader read= com.ExecuteReader())
{
while (read.Read())
{
createLabelCmd((int)read["x"], (int)read["y"]);
}
}
Or set this in your connection string;
...MultipleActiveResultSets=true;
I guess you are writing a sitting planner and try to show labels at specific positions. Therefore, you would better select all records from klient table for a given event and put them in a DataSet. Then iterate through it (using a foreach) and create the labels. This way, there is only ONE command that should be sent to database and , obviously, the performance of your application will be much better.
Having said that, I don't understand how your sittingSearch variable work and I think it needs revising.
You can either use a 2nd connection for createLabelCmd or turn on MARS (multiple active results sets) in your initial connection by adding "MultipleActiveResultSets=True" to your connection string.
http://msdn.microsoft.com/en-us/library/h32h3abf.aspx
Setting MARS to True AND
making sure i used ToList(); in my if statements and returns
in the below code i was missing the toList() in both conditions of the if statement, i was getting the error on IIS 8.5 after publishing .. updating the statement to the below worked#!
var varM = (id == 1) ? db.M.Where(x => x.UN== userID).ToList() : db.M.Where(x => x.EUN== userID).ToList();

Categories