LINQ查询使用从查询接收参数的UDF

时间:2012-09-25 09:36:31

标签: linq parameter-passing user-defined-functions

我需要在LINQ中使用UDF来帮助从一个固定点计算用户位置。

int pointX = 567, int pointY = 534; // random points on a square grid
var q = from n in _context.Users 
join m in _context.GetUserDistance(n.posY, n.posY, pointX, pointY, n.UserId) on n.UserId equals m.UserId
select new User() {
  PosX = n.PosX,
  PosY = n.PosY,
  Distance = m.Distance,        
  Name = n.Name,
  UserId = n.UserId
};

GetUserDistance只是一个UDF,它在TVP中返回一行,其中用户与在pointX和pointY变量中分离的点相距离,设计者为它生成以下内容:

[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetUserDistance", IsComposable=true)]
public IQueryable<GetUserDistanceResult> GetUserDistance([global::System.Data.Linq.Mapping.ParameterAttribute(Name="X1", DbType="Int")] System.Nullable<int> x1, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="X2", DbType="Int")] System.Nullable<int> x2, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="Y1", DbType="Int")] System.Nullable<int> y1, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="Y2", DbType="Int")] System.Nullable<int> y2, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="UserId", DbType="Int")] System.Nullable<int> userId)
{
    return this.CreateMethodCallQuery<GetUserDistanceResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), x1, x2, y1, y2, userId);
}

当我尝试编译时我得到

The name 'n' does not exist in the current context

2 个答案:

答案 0 :(得分:0)

这不是一个真正的UDF问题 - 这是一个LINQ问题。您不能在join子句的源部分中使用现有的范围变量,因此这同样是错误的:

string[] files = ...;
var query = from file in files
            join line in File.ReadAllLines(file) on file equals line
            ...

我怀疑你需要把它写成多个from子句:

var q = from n in _context.Users 
        from m in _context.GetUserDistance(n.posY, n.posY, pointX, pointY, n.UserId)
        where n.UserId == m.UserId
        ...

虽然根本不需要联接似乎有些奇怪,但是当我期望 GetUserDistance的结果只是针对该用户时,对吧?这可能更清楚:

var q = from n in _context.Users 
        let m = _context.GetUserDistance(n.posY, n.posY, pointX, pointY, n.UserId)
                        .Single()
        ...

答案 1 :(得分:0)

我认为你不需要加入,试试这个:

int pointX = 567, int pointY = 534; // random points on a square grid
var q = from n in _context.Users 
let m = _context.GetUserDistance(n.posY, n.posY, pointX, pointY, n.UserId).Single()
select new User() {
    PosX = n.PosX,
    PosY = n.PosY,
    Distance = m.Distance,        
    Name = n.Name,
    UserId = n.UserId
};