Linq To Sql的问题-实体框架 [英] Problem with Linq To Sql - Entity Framework
问题描述
我对Linq To Entity有疑问.我有2个表,分别称为会员和付款".我使用Linq代码检索数据.代码如下:
Hi, I have problem with Linq To Entity. I have 2 table called Member and Payment. I use Linq code to retrieve the data. Here''s the code:
Array array = (from member in container.Member
join payment in container.Payment
on member.MemberCode equals payment.MemberCode
select new { member.Name, member.Rank, payment.DatePaid, payment.Remarks }).ToArray();
我的问题是:如何获取此数组的每个元素?我想将每个元素添加到ListView.
通过编写dataGridView.DataSource = list可以很容易地将数组设置为DataGridView数据源;
我只想获取此数组的每个元素,因为我需要循环它们并将其插入ListView.
我无法使用此行访问它,因为此数组同时包含Member和Payment.
My question is: how to get each element of this array? I want to add each element into ListView.
It''s easy to set array as DataGridView data source by writing dataGridView.DataSource = list;
All I want here is to get each element of this array because I need to loop them and insert them into ListView.
I can''t access it with this line because this array contains both Member and Payment.
string nm = string.Empty;
string dp = string.Empty;
foreach(Member m in array)
{
nm = m.Name;
dp = m.DatePaid //It can't
}
推荐答案
之所以不能,是因为您使用的是匿名类型.
试试这个
The reason you can''t is because you are using an anonymous type.
Try this instead
var array = (from member ...
foreach(var t in array){
}
然后,使用调试器可以检查t具有哪些成员.可能是名称,职级和日期以及备注
Then using the debugger you can check what members t has. Probably name, rank and datepaid and remarks
1)您不能在知名类和匿名类之间隐式转换.
2)您构造的数组不是Member的数组
这是您的选择:
方法1)
定义一个包含要作为结果返回的所有四个成员的类,然后选择结果作为该类的枚举(...select new classname { Name=Memeber.name, ....
和foreach(classname m in array)...
)
方法2)
您可以使用反射来读取成员值.这是开销,因此要小心.
方法3)
将数组也声明为匿名数组(var array=(from...
和foreach(var m in array)...
)
方法4)
使用新的动态超类型(foreach(dynamic m in array)...
)
我宁愿使用方法1.
PS:您应该只在真正需要时才将其转换为数组,因为您错过了延迟执行的优点.
1) You can not cast implicitly between well-known and anonymous classes.
2) The array you construct is not an array of Member
Here are your options:
Method 1)
Define a class that contains all four members you want to return as result, and select the result as enumeration of that class (...select new classname { Name=Memeber.name, ....
andforeach(classname m in array)...
)
Method 2)
You can use reflection to read the member values. This is an overhead, thus be careful.
Method 3)
Declare the array also as anonymous (var array=(from...
andforeach(var m in array)...
)
Method 4)
Use the new dynamic supertype (foreach(dynamic m in array)...
)
I would rather use method 1.
PS: You should convert it to array only when really needed, since you miss the advantages of deferred execution.
这篇关于Linq To Sql的问题-实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!