无法将类型“System.Nullable`1”强制转换为类型“System.Object”。LINQ to Entities 仅支持强制转换 EDM 基元或枚举类型。

在一个项目中使用LINQ和EF时出现了题目所示的异常,搜索了很多资料都找不到解决办法,主要是因为EF方面的知识欠缺。

先将情况记录如下,以供以后参考。

查询主要设计两张表,由外键关联:

  无法将类型“System.Nullable`1”强制转换为类型“System.Object”。LINQ to Entities 仅支持强制转换 EDM 基元或枚举类型。

在进行下面的查询时,出现异常:无法将类型“System.Nullable`1”强制转换为类型“System.Object”。LINQ to Entities 仅支持强制转换 EDM 基元或枚举类型。

 public ActionResult GetIpSegments()
{
//List<Ipsegment> ipsegments = (from s in deviceDB.Ipsegment select s).ToList();
var ipsegments = from d in deviceDB.DeviceCategory
join s in deviceDB.Ipsegment
on d.devicecategoryid equals s.devicecategoryid
select new
{
devicecategoryid1 = s.devicecategoryid,
devicecategoryname1 = d.devicecategoryname,
ipsegment = "202.115.242." + s.ip_head + "-202.115.242." + s.ip_end
}; return Json(ipsegments, JsonRequestBehavior.AllowGet);
}

后来,对查询做了修改,才成功。修改后的查询如下所示:

    public ActionResult GetIpSegments()
{
var ipsegments = from s in deviceDB.Ipsegment
select new
{
s.devicecategoryid,
s.DeviceCategory.devicecategoryname,
s.ip_head,
s.ip_end
}; return Json(ipsegments, JsonRequestBehavior.AllowGet);
}

这其中的原因,现在还不了解,等了解后再作补充。

上一篇:我的WCF Data Service 系列 (一、为什么要有WCF Data Service)


下一篇:Python 可变对象和不可变对象