调用数据库功能的实体框架6 [英] Calling DB Function with Entity Framework 6

查看:131
本文介绍了调用数据库功能的实体框架6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照这些说明添加一个标量函数到我的实体框架6的数据模型。
<一href=\"http://stackoverflow.com/questions/12481868/how-to-use-scalar-valued-function-with-linq-to-entity\">How使用标量值函数使用LINQ到实体?

不过,我不能够调用LINQ查询中的函数,虽然直接调用该方法的DataContext的工作。

 使用(实体上下文=新的实体()){
    //这工作。
    变种测试1 = context.fn_GetRatingValue(8,9,0).FirstOrDefault();
    //这是行不通的。
    变种的Test2 =(从context.MediaRatingsř
                选择context.fn_GetRatingValue(r.Height,r.Depth,0))了ToList()。
}

第二个查询抛出这个错误。

  LINQ到实体无​​法识别方法System.Data.Entity.Core.Objects.ObjectResult`1 [System.Nullable`1 [System.Single] fn_GetRatingValue(系统。 Nullable`1 [System.Single],System.Nullable`1 [System.Single],System.Nullable`1 [System.Single])的方法,而这种方法不能被翻译成店前pression。

此外,设计师给我这个警告

 错误6046:无法生成存储功能fn_GetRatingValue'的函数导入的返回类型。这家商店的功能将被忽略,不会生成函数导入。

我是什么做错了吗?我怎样才能调用数据库功能的LINQ查询中?

另外,如果查询code有时候会针对数据库,有时在内存中执行,有没有办法来调用,在这两种情况下的工作方式的功能?我也有同样的功能的C#版本。

感谢

编辑:这里是我想要使用的功能

 公众持股量?的GetValue(浮动?身高,浮?深度,浮动比率){
    如果(高度!= NULL ||深!= NULL){
        浮HeightCalc =身高? Depth.Value;
        浮DepthCalc =深度? Height.Value;
        如果(比率℃,)
            DepthCalc = DepthCalc +(HeightCalc - DepthCalc)* -ratio;
        否则如果(比率大于0)
            HeightCalc = HeightCalc +(DepthCalc - HeightCalc)*比例;
        回报(浮)Math.Round(HeightCalc * DepthCalc * 0.12,1);
    }其他
        返回null;
}

它也可以被写成这样一行。这条线可以复制/粘贴无处不在我需要使用它,但是这将产生非常难看code,虽然可以工作。我宁愿保持它作为一个功能。

 收益率(浮)Math.Round(
    (Height.HasValue Height.Value +(比率大于0((深度?? Height.Value) - Height.Value)*比率:?0):Depth.Value)*
    (Depth.HasValue Depth.Value +(比率℃,((身高?? Depth.Value) - Depth.Value)* -ratio:?0):Height.Value)
    * 0.12,1);


解决方案

我找到了答案。虽然我能找到的关于实体框架6中EdmFunctionAttribute是过时很少的文档,我得到这个code工作。

在EDMX文件,IsComposable必须真实在CommandText必须拆除。我只需要在函数声明没有函数导入。

然后,在部分类我的数据上下文,我创造了这个功能。

  [DbFunction(NaturalGroundingVideosModel.Store,fn_GetRatingValue)]
公众持股量? DbGetValue(浮动?高度,浮?深度,浮动比率){
    清单&LT; ObjectParameter&GT;参数=新的List&LT; ObjectParameter&GT;(3);
    parameters.Add(新ObjectParameter(高度,高度));
    parameters.Add(新ObjectParameter(深度,深度));
    parameters.Add(新ObjectParameter(比率,比));
    变种lObjectContext =((IObjectContextAdapter)此).ObjectContext;
    无功输出= lObjectContext。
            &的createQuery LT;浮动&GT;(NaturalGroundingVideosModel.Store.fn_GetRatingValue(@height,@depth,@ratio),parameters.ToArray())
        .Execute(MergeOption.NoTracking)
        .FirstOrDefault();
    返回输出;
}

我添加功能到MediaRating对象这样我就可以把它无需数据上下文的参考。

  VAR的Test2 =(从context.MediaRatingsř
    选择r.DbGetValue(r.Height,r.Depth,0))了ToList()。

这个作品!

I followed these instructions to add a scalar function into my Entity Framework 6 data model. How to use scalar-valued function with linq to entity?

However, I'm not able to call the function within a LINQ query, although calling the method directly on the DataContext works.

using (Entities context = new Entities()) {
    // This works.
    var Test1 = context.fn_GetRatingValue(8, 9, 0).FirstOrDefault();
    // This doesn't work.
    var Test2 = (from r in context.MediaRatings
                select context.fn_GetRatingValue(r.Height, r.Depth, 0)).ToList();
}

The second query throws this error.

LINQ to Entities does not recognize the method 'System.Data.Entity.Core.Objects.ObjectResult`1[System.Nullable`1[System.Single]] fn_GetRatingValue(System.Nullable`1[System.Single], System.Nullable`1[System.Single], System.Nullable`1[System.Single])' method, and this method cannot be translated into a store expression.

Also, the designer is giving me this warning

Error 6046: Unable to generate function import return type of the store function 'fn_GetRatingValue'. The store function will be ignored and the function import will not be generated.

What am I doing wrong? How can I call the database function within a LINQ query?

Also, if the query code sometimes gets executed against the database and sometimes in-memory, is there a way to call the function in a way that works in both cases? I have a C# version of the same function.

Thanks

Edit: Here's the function I'm trying to use.

public float? GetValue(float? Height, float? Depth, float ratio) {
    if (Height != null || Depth != null) {
        float HeightCalc = Height ?? Depth.Value;
        float DepthCalc = Depth ?? Height.Value;
        if (ratio < 0)
            DepthCalc = DepthCalc + (HeightCalc - DepthCalc) * -ratio;
        else if (ratio > 0)
            HeightCalc = HeightCalc + (DepthCalc - HeightCalc) * ratio;
        return (float)Math.Round(HeightCalc * DepthCalc * .12, 1);
    } else
        return null;
}

It can also be written in one line like this. This line could be copy/pasted everywhere I need to use it but that would produce very ugly code, although that could work. I'd rather keep it as a function.

return (float)Math.Round(
    (Height.HasValue ? Height.Value + (ratio > 0 ? ((Depth ?? Height.Value) - Height.Value) * ratio : 0) : Depth.Value) *
    (Depth.HasValue ? Depth.Value + (ratio < 0 ? ((Height ?? Depth.Value) - Depth.Value) * -ratio : 0) : Height.Value)
    * .12, 1);

解决方案

I found the answer. Although I could find very little documentation about Entity Framework 6 in which EdmFunctionAttribute is obsolete, I got this code to work.

In the EDMX file, IsComposable must be True and the CommandText must be removed. I need only the function declaration without the function import.

Then, in a partial class of my data context, I created this function

[DbFunction("NaturalGroundingVideosModel.Store", "fn_GetRatingValue")]
public float? DbGetValue(float? height, float? depth, float ratio) {
    List<ObjectParameter> parameters = new List<ObjectParameter>(3);
    parameters.Add(new ObjectParameter("height", height));
    parameters.Add(new ObjectParameter("depth", depth));
    parameters.Add(new ObjectParameter("ratio", ratio));
    var lObjectContext = ((IObjectContextAdapter)this).ObjectContext;
    var output = lObjectContext.
            CreateQuery<float?>("NaturalGroundingVideosModel.Store.fn_GetRatingValue(@height, @depth, @ratio)", parameters.ToArray())
        .Execute(MergeOption.NoTracking)
        .FirstOrDefault();
    return output;
}

I added the function to the MediaRating object so I can call it without needing a reference to the data context.

var Test2 = (from r in context.MediaRatings
    select r.DbGetValue(r.Height, r.Depth, 0)).ToList();

This works!

这篇关于调用数据库功能的实体框架6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆