SharePoint 2010 增加了对LINQ的支持,增强了开发的能力。那么其中好事有一些晓得细节需要我们注意的。
例子:有一个自定义列表“Citys”, 其中包含一个”选项”类型的字段“GDP”,它包含如下的两个选项:
那么你有没有尝试过如何去使用LINQ获得这列的值,我们来看一下:
首先使用SPMetal工具生成实体类,我们在实体类中找到“GDP”这个字段:
internal enum GDP : int
{
None = 0,
Invalid = 1,
[Microsoft.SharePoint.Linq.ChoiceAttribute(Value = "5 per user/month")]
_5PerUserMonth = 2,
[Microsoft.SharePoint.Linq.ChoiceAttribute(Value = "10 per company/month")]
_10PerCompanyMonth = 4,
}
如果这个时候,你直接使用
item.GDP.Value
来获得这列的值,那么你得到的肯定是“_5PerUserMonth” 或者 “_10PerCompanyMonth” , 而没有办法得到他真正的值。谁叫C#的变量命名规则不让使用“空格”或者“/”等呢。这个时候我们需要利用发射来获取到里面的值。
public void GetGDP()
{
var ctx =
new CityDataContext(WebUrl);
var cityList = from c in ctx.Citys
select c;
foreach (var item in cityList)
{
Console.WriteLine(stringValueOf(item.GDP));
}
}
public string stringValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
Microsoft.SharePoint.Linq.ChoiceAttribute[] attributes =
(Microsoft.SharePoint.Linq.ChoiceAttribute[])fi.GetCustomAttributes(
typeof(Microsoft.SharePoint.Linq.ChoiceAttribute),false);
if (attributes.Length > 0)
{
return attributes[0].Value;
}
else
{
return value.ToString();
}
}
如果列表中的其他列里面也存有这样的值,那么你使用的时候还真的要注意了。