2012-09-25 30 views
0

我需要在LINQ中使用UDF的帮助,它可以从固定点计算用户位置。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和尖尖的变量deisgnated点用户的距离,设计者生成了下列文件:

[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 

回答

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() 
     ... 
+0

乔恩的第二个答案非常完美,用“让”的条款 - 我试过失败但没有.Single()。非常感谢你。 @Wasp - 这和你的回答是一样的,但是我必须选择Jons repsonse,因为它是第一个,并且提供了几个scnearios来尝试,但是感谢你们俩 –

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

Jon当然更快了,并且让我发现了我错过的东西, 。 – Wasp