无法运行模型定义的函数

时间:2012-12-27 21:28:25

标签: linq entity-framework entity-framework-4 edmx

例外:

  

System.NotSupportedException:类型为“Zx.Data.zxEntities”的指定方法“Int32 CastToInt(System.String)”无法转换为LINQ to Entities存储表达式,因为调用它的实例不是使用它的查询的ObjectContext。

.edmx文件声明:

<!-- CSDL content -->
<edmx:ConceptualModels>
  <Schema Namespace="zxModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
  <!-- blah-blah-blah -->
  <Function Name="CastToInt" ReturnType="Edm.Int32" >
    <Parameter Name="p" Type="Edm.String" />
    <DefiningExpression>
      CAST (p AS Edm.Int32)
    </DefiningExpression>
  </Function>
  </Schema>
</edmx:ConceptualModels>

.Net功能声明:

namespace Zx.Data
{
    using System;
    using System.Data.Objects;
    using System.Data.Objects.DataClasses;

    public partial class zxEntities  
    {
        [EdmFunction("zxModel", "CastToInt")]
        public int CastToInt(String p)
        {
            throw new NotSupportedException("This function is only for L2E query.");
        }
    }
}

调用函数:

var suppliers = entities.tblFirmPrice.Where(x => x.cat_Id == item.Cat_id)
    .Join(entities.Firms, fp => fp.frm_Id, f => f.Frm_Id,
        (fp, f) => new
        {
            fp.frm_Id,
            Price = fp.fp_FirmPrice,
            Discount = entities.tblFirmDiscount.Where(
                       x => entities.CastToInt(x.frm_id) == fp.frm_Id)
                       .OrderByDescending(x => x.fd_id)
                       .Select(x => x.fd_discount)
                       .FirstOrDefault(),
            PriceMarkup = entities.CastToInt(
                          SqlFunctions.StringConvert(f.Frm_IcsAdd))
        })
        .Select(x => new
        {
            x.frm_Id,
            Price = x.Price * (1 - ((((int?)x.Discount) ?? 0) / 100M)),
            x.PriceMarkup
        });

:-( 有什么建议吗?

P.S。:编码时,使用http://msdn.microsoft.com/en-us/library/dd456857.aspxhttp://msdn.microsoft.com/en-us/library/dd456857.aspx

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用Convert.ToInt32方法?

Discount = entities.tblFirmDiscount.Where(
              x => Convert.ToInt32(x.frm_id) == fp.frm_Id)