我正在实现一个将使用 Entity Framework 6获取数据的Web api。我正在使用Sql Server 2014和Visual Studio2015。在调试CustomerDao类中的代码时,尽管可以看到记录,但在customerOrderContext对象中却看到异常在客户对象中。但是,在using块执行后,我看不到任何记录。
((System.Data.SqlClient.SqlConnection)customerOrderContext.Database.Connection).ServerVersion
客户Dao
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
}).ToList();
}
配置文件中的连接字符串如下
<add name="Entities" connectionString="metadata=res://*/EF.CustomerOrderContext.csdl|res://*/EF.CustomerOrderContext.ssdl|res://*/EF.CustomerOrderContext.msl;provider=System.Data.SqlClient;provider connection string="data source=Tom-PC\MSSQLSERVER2014;initial catalog=Ransang;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
上下文类遵循
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; }
}
CustomProvider.cs
public IEnumerable<BusinessObjects.Customers> GetAllCustomers()
{
IList<BusinessObjects.Customers> customerCollection = new List<BusinessObjects.Customers>();
dataAccess.CustomerDao.GetAllCustomers();
return customerCollection;
}
最佳答案
异常(exception)是documented,这是因为连接已关闭。这没有问题。
但是显然您会得到空结果,因为您没有使用结果,只是在方法中返回了new List<BusinessObjects.Customers>()
:
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
}
您需要
return dataAccess.CustomerDao.GetAllCustomers();
:关于c# - Entity Framework 6错误服务器版本: (System.(Data.SqlClient.SqlConnection)customerOrderContext.Database.Connection).ServerVersion,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40391054/