EzDevInfo.com

ado.net interview questions

Top ado.net frequently asked interview questions

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I am getting following error when i am trying to connect Production DB from Local Environment.

I was able to connect Production DB before, but suddenly i am getting following error, any idea?

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 0 - The handle is invalid.)

I was trying to run asp.net website in local PC, which has connection string of Production DB, following is stack trace for error i am getting in local environment.

at MyWebsiteDAL.clsForumQuestion.SelectAll(Int32 CurrentPageIndex, Int32 PageSize) in D:\EDrive\My WebSites\MyWebsite\MyWebsite\MyWebsiteDAL\clsForumQuestion.cs:line 821
   at CodeConnect.Default.Page_Load(Object sender, EventArgs e) in D:\EDrive\My WebSites\MyWebsite\MyWebsite\MyWebsite\Default.aspx.cs:line 100
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
   at System.Web.UI.Control.OnLoad(EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Any idea what might have gone wrong here?


Source: (StackOverflow)

Entity Framework Vote of No Confidence - relevant in .NET 4?

I'm deciding on an ORM for a big project and was determined to go for ADO.NET Entity Framework, specifically its new version that ships with .NET 4. During my search for information on EF I stumbled upon ADO .NET Entity Framework Vote of No Confidence which I'm not sure how to take.

The Vote of No Confidence was written sometime in 2008 to convince Microsoft to listen to specific criticism for EF v1.

It's not clear whether the claims made in the Vote of No Confidence are still valid (in .NET 4) and if they're serious enough to use other solutions. NHibernate is a mature alternative, but I don't know what problems it brings. I'm generally more inclined towards a Ms solution, mainly because I can count on integration with VS and on their developer support.

I would appreciate examples of how the problems mentioned in the Vote of No Confidence affect in real world projects. More importantly, are the claims made there still relevant in EF for .NET 4?


Source: (StackOverflow)

Advertisements

Microsoft.ACE.OLEDB.12.0 provider is not registered

I have a Visual Studio 2008 solution with two projects (a Word-Template project and a VB.Net console application for testing). Both projects reference a database project which opens a connection to an MS-Access 2007 database file and have references to System.Data.OleDb. In the database project I have a function which retrieves a data table as follows

 private class AdminDatabase
   ' stores the connection string which is set in the New() method
   dim strAdminConnection as string

   public sub New()
   ...
   adminName = dlgopen.FileName
   conAdminDB = New OleDbConnection
   conAdminDB.ConnectionString = "Data Source='" + adminName + "';" + _
       "Provider=Microsoft.ACE.OLEDB.12.0"

   ' store the connection string in strAdminConnection
   strAdminConnection = conAdminDB.ConnectionString.ToString()
   My.Settings.SetUserOverride("AdminConnectionString", strAdminConnection)
   ...
   End Sub

   ' retrieves data from the database
   Public Function getDataTable(ByVal sqlStatement As String) As DataTable
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim da As New OleDbDataAdapter
        Dim localCon As New OleDbConnection


        localCon.ConnectionString = strAdminConnection

        Using localCon
            Dim command As OleDbCommand = localCon.CreateCommand()
            command.CommandText = sqlStatement
            localCon.Open()
            da.SelectCommand = command
            da.Fill(dt)
            getDataTable = dt
        End Using

    End Function
End Class

When I call this function from my Word 2007 Template project everything works fine; no errors. But when I run it from the console application it throws the following exception

ex = {"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."}

Both projects have the same reference and the console application did work when I first wrote it (a while ago) but now it has stopped work. I must be missing something but I don't know what. Any ideas?


Source: (StackOverflow)

ADO.NET Entity Framework: Update Wizard will not add tables

I added a new ADO.Net Entity Data Model into my project and used the Update Wizard to add tables into the model. Five of the selected tables were added to the design surface. Two other tables will not add. I select them in the wizard and click Finish, yet they never show up on the design surface.

Is this a bug, or are there some situations where a table cannot be added to the model (by design)?


UPDATE: The XML (*.edmx) reveals the problem.

<!--Errors Found During Generation:
warning 6013: The table/view 'FooBar.dbo.Roles' does not 
have a primary key defined and no valid primary key could be inferred. 
This table/view has been excluded. To use the entity you will need to 
review your schema, add the correct keys and uncomment it.-->
<!--<EntityType Name="Roles">
    <Property Name="role_id" Type="decimal" />
    <Property Name="role_desc" Type="nvarchar" MaxLength="30" />
</EntityType>-->

Thanks Craig for your response.


Source: (StackOverflow)

How can i query for null values in entity framework?

I want to execute a query like this

   var result = from entry in table
                     where entry.something == null
                     select entry;

and get an IS NULL generated.

Edited: After the first two answers i feel the need to clarify that I'm using Entity Framework and not Linq to SQL. The object.Equals() method does not seem to work in EF.

Edit no.2: The above query works as intended. It correctly generates IS NULL. My production code however was

value = null;
var result = from entry in table
                         where entry.something == value
                         select entry;

and the generated SQL was something = @p; @p = NULL. It seems that EF correctly translates the constant expression but if a variable is involved it treats it just like a normal comparison. Makes sense actually. I'll close this question


Source: (StackOverflow)

DbArithmeticExpression arguments must have a numeric common type

TimeSpan time24 = new TimeSpan(24, 0, 0);
TimeSpan time18 = new TimeSpan(18, 0, 0);    

// first get today's sleeping hours
List<Model.Sleep> sleeps = context.Sleeps.Where(
    o => (clientDateTime - o.ClientDateTimeStamp < time24) && 
          o.ClientDateTimeStamp.TimeOfDay > time18 && 
          clientDateTime.TimeOfDay < time18 && 
          o.UserID == userid).ToList(); 

This Linq expression throws this exception:

DbArithmeticExpression arguments must have a numeric common type.

Please Help!


Source: (StackOverflow)

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

I am trying to save Employee details, which has references with City. But everytime I try to save my contact, which is validated I get the exception "ADO.Net Entity Framework An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

I had read so many post but still not getting the exact idea of what to do... my Save button click code is given below

protected void Button1_Click(object sender, EventArgs e)
    {
        EmployeeService es = new EmployeeService();
        CityService cs = new CityService();

        DateTime dt = new DateTime(2008, 12, 12);
        Payroll.Entities.Employee e1 = new Payroll.Entities.Employee();

        Payroll.Entities.City city1 = cs.SelectCity(Convert.ToInt64(cmbCity.SelectedItem.Value));

        e1.Name = "Archana";
        e1.Title = "aaaa";
        e1.BirthDate = dt;
        e1.Gender = "F";
        e1.HireDate = dt;
        e1.MaritalStatus = "M";
        e1.City = city1;        

        es.AddEmpoyee(e1,city1);
    }

and Employeeservice Code

public string AddEmpoyee(Payroll.Entities.Employee e1, Payroll.Entities.City c1)
        {
            Payroll_DAO1 payrollDAO = new Payroll_DAO1();
            payrollDAO.AddToEmployee(e1);  //Here I am getting Error..
            payrollDAO.SaveChanges();
            return "SUCCESS";
        }

Source: (StackOverflow)

ADO.NET DataRow - check for column existence

How do I check for the existence of a column in a datarow?

I'm building datatables to organize some data that I've already pulled back from the database. Depending on the type of data in each row, I need to create a datatable with different columns. Then, later on, I want to check and see if the datatable I am looking at has a certain column.

I know I can catch the exception and handle it that way, but I'm curious if there is a property or method on the datarow object that will do this for me?

Here's how I can do it by catching the exception:

public static String CheckEmptyDataRowItem(DataRow row, String rowName, String nullValue)
{
    try
    {
        return row[rowName].ToString();
    }
    catch (System.ArgumentException)
    {
        return nullValue;
    }
}

Source: (StackOverflow)

Get output parameter value in ADO.NET

My stored procedure has an output parameter:

@ID INT OUT

How can I retrieve this using ado.net?

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters

    conn.Open();

    // *** read output parameter here, how?
    conn.Close();
}

Source: (StackOverflow)

Connection timeout for SQL server

Can I increase the timeout by modifying the connection string in the web.config?


Source: (StackOverflow)

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

What are the different cases when we use these three? Where should I use one and where should I not?


Source: (StackOverflow)

How to create a DataTable in C# and how to add rows?

How do create a DataTable in C#?

I did like this:

 DataTable dt = new DataTable();
 dt.clear();
 dt.Columns.Add("Name");
 dt.Columns.Add("Marks");

How do I see the structure of DataTable?

Now I want to add ravi for Name and 500 for Marks. How can I do this?


Source: (StackOverflow)

Entity Framework with NOLOCK

How can I use the NOLOCK function on Entity Framework? Is XML the only way to do this?


Source: (StackOverflow)

Get the generated SQL-Statement from a SqlCommand-Object?

I have the following code:

Using cmd As SqlCommand = Connection.CreateCommand
    cmd.CommandText = "UPDATE someTable SET Value = @Value"
    cmd.CommandText &= " WHERE Id = @Id"
    cmd.Parameters.AddWithValue("@Id", 1234)
    cmd.Parameters.AddWithValue("@Value", "myValue")
    cmd.ExecuteNonQuery
End Using

I wonder if there is any way to get the final SQL-Statment as a String, which should look like this:

UPDATE someTable SET Value = "myValue" WHERE Id = 1234

If anyone wonders why I would do this:

  • for logging (failed) statements
  • for having the possibility to copy & paste it to the Enterprise Manager for testing purposes

Source: (StackOverflow)

Mixed mode assembly is built against version ‘v2.0.50727′ of the runtime

I'm getting the following exception:

Mixed mode assembly is built against version ‘v2.0.50727′ of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

as I was trying to export crystal report from my WPF program...

I have added the following in the app.config already...

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<runtime>
  <NetFx40_LegacySecurityPolicy enabled="true"/>
</runtime>

Any experts can help????

Reference I found: http://www.davidmoore.info/2010/12/17/running-net-2-runtime-applications-under-the-net-4-runtime


Source: (StackOverflow)