0

I need help using a UDF in a LINQ which calculates a users position from a fixed point.

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

The GetUserDistance is just a UDF that returns a single row in a TVP with that users distance from the points deisgnated in pointX and pointY variables, and the designer generates the following for it:

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

when i try to compile i get

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

2 回答 2

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
};
于 2012-09-25T09:44:38.150 回答
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()
        ...
于 2012-09-25T09:41:00.450 回答