我有这种功能。现在我不知道如何调用它来从字段中获取数据。
public static IEnumerable GetMaterialSearch(int reqNo)
{
DataClassesCRMDataContext dbContext = new DataClassesCRMDataContext();
try
{
var res = from tbl1 in dbContext.MaterialApplicants
join tbl2 in dbContext.MaterialRequests on tbl1.ApplicantID equals tbl2.Applicant
where tbl2.RCD_ID == reqNo
select new
{
Crusher = tbl2.Crusher,
ApplicantID = tbl2.Applicant,
Comments = tbl2.Comments,
ReqDate = tbl2.ReqDate,
Operator = tbl2.Operator,
Title = tbl1.Title,
Applicant = tbl1.Applicant,
Address = tbl1.Address,
Nationality = tbl1.Nationality,
HouseNo = tbl1.HouseNo,
MobileNo = tbl1.MobileNo,
};
if (res.Count() > 0)
{
return res.ToList();
}
return null;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
return null;
}
finally
{
dbContext.Connection.Close();
}
}
答案 0 :(得分:5)
IEnumerable
是一个通常用于迭代的序列:
var result = GetMaterialSearch(42);
if (result != null)
foreach (var entry in result)
DoSomething(entry);
修改:如上所述,代码的问题在于您在IEnumerable
结果中返回了匿名类型。匿名类型不旨在跨越方法边界。来自Anonymous Types (C# Programming Guide):
您不能将方法的字段,属性,事件或返回类型声明为具有匿名类型。 [...]要将匿名类型或包含匿名类型的集合作为方法的参数传递,可以将参数声明为类型对象。但是,这样做会破坏强类型的目的。如果必须存储查询结果或将它们传递到方法边界之外,请考虑使用普通的命名结构或类而不是匿名类型。
如果您绝对不想创建命名类,可以使用反射来访问您的字段,例如通过C#4中引入的dynamic
关键字:
var result = GetMaterialSearch(42);
if (result != null)
foreach (dynamic entry in result)
Console.WriteLine(entry.ID);
答案 1 :(得分:2)
您的方法返回非泛型IEnumerable
,这就是问题所在。您应该将其更改为通用IEnumerable<T>
,但需要创建另一个类:
class MaterialItem
{
public string Crusher { get; set; }
public int ApplicantID { get; set; }
// (...)
}
然后更改您的方法签名:
public static IEnumerable<MaterialItem> GetMaterialSearch(int reqNo)
并将您的查询更改为返回MaterialItem
而不是匿名类型对象:
var res = from tbl1 in dbContext.MaterialApplicants
join tbl2 in dbContext.MaterialRequests on tbl1.ApplicantID equals tbl2.Applicant
where tbl2.RCD_ID == reqNo
select new MaterialItem
{
Crusher = tbl2.Crusher,
ApplicantID = tbl2.Applicant,
Comments = tbl2.Comments,
ReqDate = tbl2.ReqDate,
Operator = tbl2.Operator,
Title = tbl1.Title,
Applicant = tbl1.Applicant,
Address = tbl1.Address,
Nationality = tbl1.Nationality,
HouseNo = tbl1.HouseNo,
MobileNo = tbl1.MobileNo,
};
但这不是我要做的唯一改变。调用Count()
以后调用ToList()
会导致不必要的数据库调用。
我会选择:
var results = res.ToList();
if(results.Any())
return results;
return null;