我有一个简单的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Entity;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NuLabsEntities db = new NuLabsEntities();
IEnumerable<company> companies = from cmp in db.company select cmp;
foreach (var row in companies)
{
Console.WriteLine(companies);
Console.ReadLine();
}
}
}
}我知道这是一个基本的问题:我正在学习c#
但是,我不明白为什么在使用ado.net创建了一个edmx文件并尝试运行这个简单的代码之后,它将返回以下查询,而不是返回公司表的行列表的结果:
SELECT
[Extent1].[companyId] AS [companyId],
[Extent1].[labirintoCodiceCliente] AS [labirintoCodiceCliente],
[Extent1].[labirintoCodiceAteco2007] AS [labirintoCodiceAteco2007],
[Extent1].[name] AS [name],
[Extent1].[doc] AS [doc],
[Extent1].[notes] AS [notes],
[Extent1].[vatNumber] AS [vatNumber],
[Extent1].[taxCode] AS [taxCode],
[Extent1].[LabirintoFornitoreId] AS [LabirintoFornitoreId],
[Extent1].[LabirintoCommercialistaId] AS [LabirintoCommercialistaId],
[Extent1].[LabirintoConsulenteDelLavoroId] AS [LabirintoConsulenteDelLavoroId]
FROM [dbo].[company] AS [Extent1]发布于 2015-09-15 13:52:18
Console.WriteLine(companies);应该是Console.WriteLine(row.blah);.ToList(),然后循环遍历集合。查询是在调用ToList()时计算的。使用您已经编码的foreach,您可以将每个company排在行中。您可以从company访问row的属性。
假设您的comany结构是这样的
public class company
{
public int companyId {get;set;}
public string companyName {get;set;}
}你的代码应该是
foreach (var row in companies.ToList())
{
Console.WriteLine("CompanyId:"+row.CompanyId.ToString());
Console.WriteLine("CompanyName:"+row.CompanyName);
Console.ReadLine();
}发布于 2015-09-15 13:52:52
我想你应该传递行对象
Console.WriteLine(row);发布于 2015-09-15 13:58:58
为什么?
因为公司的类型是System.Data.Entity.Infrastructure.DbQuery<Company>,所以它的ToString()方法返回查询。
当您使用Console.WriteLine(somthings)时,某些东西的ToString方法将用于输出数据,因此您将收到ToString结果,即查询文本。
如何重新生成值?
要获取字段的值,可以在循环中使用Console.WriteLine(row.SomeField);接收行的SomeField值。
Note
请记住,Console.WriteLine(row);将输出您公司类的类型,并且输出将是每个行的类名。
https://stackoverflow.com/questions/32587866
复制相似问题