복붙노트

[SQL] 엔티티 프레임 워크 6 호출 DB 기능

SQL

엔티티 프레임 워크 6 호출 DB 기능

내 엔티티 프레임 워크 (6 개) 데이터 모델로 스칼라 함수를 추가하려면 다음 지침을 따랐다. 어떻게 엔티티에 LINQ와 스칼라 반환 함수를 사용하는 방법?

DataContext를 작품에 직접 메소드를 호출하지만, 그러나, 나는은 LINQ 쿼리 내에서 함수를 호출 할 수 아니에요.

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();
}

두 번째 쿼리는이 오류가 발생합니다.

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.

또한, 설계자는 나에게이 경고를주고있다

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.

내가 무엇을 잘못하고 있지? 어떻게 LINQ 쿼리 내에서 데이터베이스 함수를 호출 할 수 있습니다?

쿼리 코드가 때로는 데이터베이스에 대해 실행 및 도착 경우에도 때때로 인 - 메모리, 두 경우 모두에서 작동하는 방법으로 함수를 호출하는 방법은 무엇입니까? 나는 동일한 기능의 C # 버전이있다.

감사

편집 : 여기 내가 사용하려고 해요 함수입니다.

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;
}

또한이 같은 한 줄에 쓸 수 있습니다. 이 줄 수 복사 / 나는 그것을 사용할 필요하지만 매우 추한 코드를 생성 할 모든 곳에서 그 일을 할 수 있지만, 붙여 넣기. 차라리 함수로 유지하는 것입니다.

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);

해결법

  1. ==============================

    1.나는 답을 발견했다. 내가 EdmFunctionAttribute이 쓸모있는 엔티티 프레임 워크 (6)에 대한 아주 작은 문서를 찾을 수 있지만, 나는 일에이 코드를 얻었다.

    나는 답을 발견했다. 내가 EdmFunctionAttribute이 쓸모있는 엔티티 프레임 워크 (6)에 대한 아주 작은 문서를 찾을 수 있지만, 나는 일에이 코드를 얻었다.

    EDMX 파일에서 IsComposable는 사실이어야하며 CommandText에 제거해야합니다. 나는 함수 수입이없는 경우에만 함수 선언이 필요합니다.

    그런 다음 내 데이터 컨텍스트의 부분 클래스에서,이 기능을 생성

    [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 데이터 컨텍스트에 대한 참조를 필요로하지 않고 전화를 할 수 있도록 I는 MediaRating 객체에 기능을 추가했다.

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

    이 작품!

  2. from https://stackoverflow.com/questions/27008369/calling-db-function-with-entity-framework-6 by cc-by-sa and MIT license