这是我第一次使用Entity Framework Code First,我试图以这种方式toString()
:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Email { get; set; }
public string InterestIn { get; set; }
public virtual ICollection<User> Friends { get; set; }
public virtual ICollection<User> FromWhomIsFriend { get; set; }
public override string ToString()
{
string output = string.Empty;
output = String.Format("UserId: {0}, Name: {1}, Age: {2}, City: {3}, " +
"Country: {4}, Email: {5}, InterestIn: {6}, Friends: {7}",
UserId, Name, Age, City, Country, Email, InterestIn, Friends);
return output;
}
}
当我toString()
时,我收到此错误:
'System.Data.EntityCommandExecutionException'
"There is already an open datareader associated with this command you must close it first."
我这样做:
private static void showUsers()
{
using (var context = new AdnLineContext())
{
var users = from u in context.Users
select u;
foreach (User user in users)
{
Console.WriteLine(user.ToString());
}
}
}
我不明白,为什么我得到它?我该如何解决?
答案 0 :(得分:0)
尝试使用.ToList()强制查询执行(默认情况下,查询的执行将推迟到您枚举之前):
private static void showUsers()
{
using (var context = new AdnLineContext())
{
var users = context.Users.ToList();
foreach (User user in users)
{
Console.WriteLine(user.ToString());
}
}
}
如果失败,您也可以尝试将MultipleActiveResultSets=True
添加到连接字符串配置中,例如:
<add name="YourContext" connectionString="Data Source=.;Initial Catalog=YourDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />