Tom Tom - 1 year ago 127
C# Question

Entity Framework 6 error serverversion : (System.Data.SqlClient.SqlConnection)customerOrderContext.Database.Connection).ServerVersion

I am implementing a web api that will fetch data using entity framework 6. I am using Sql Server 2014 and visual studio 2015.While debugging the the code in the CustomerDao class I am seeing an exception in the customerOrderContext object though I can see the records in the customer object. However after the using block executes I cant see any records.



using (var customerOrderContext = new Entities())
return (from customer in customerOrderContext.Customers

select new CustomerOrder.BusinessObjects.Customers
Id = customer.Id,
FirstName = customer.FirstName,
LastName = customer.LastName,
Address = customer.Address,
City = customer.City,
Email = customer.Email,
Gender = customer.Gender,
State = customer.State,
Zip = customer.Zip

The connection string in the config file is as follows

<add name="Entities" connectionString="metadata=res://*/EF.CustomerOrderContext.csdl|res://*/EF.CustomerOrderContext.ssdl|res://*/EF.CustomerOrderContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Tom-PC\MSSQLSERVER2014;initial catalog=Ransang;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

The context class is follows

public partial class Entities : DbContext
public Entities()
: base("name=Entities")

protected override void OnModelCreating(DbModelBuilder modelBuilder)


public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<OrderDetail> OrderDetails { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }

enter image description here


public IEnumerable<BusinessObjects.Customers> GetAllCustomers()
IList<BusinessObjects.Customers> customerCollection = new List<BusinessObjects.Customers>();
return customerCollection;

Answer Source

The exception is documented and it's because the connection is closed. There is no problem with this.

But obviously you get empty result because you didn't use the result, you are just returning new List<BusinessObjects.Customers>() in your method:

public IEnumerable<BusinessObjects.Customers> GetAllCustomers()
    IList<BusinessObjects.Customers> customerCollection = 
        new List<BusinessObjects.Customers>(); // ← An empty list
    dataAccess.CustomerDao.GetAllCustomers();  // ← Just executed but didn't use anywhere
    return customerCollection;                 // ← The empty list you created at first

You need to return dataAccess.CustomerDao.GetAllCustomers();:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download