我正在使用linq来实现sql。我正在运行一个查询,它使用一个函数来返回正确的记录。我正在使用一个函数,所以我可以使用if语句,我不知道如何在linq子句中做到这一点。代码复制如下。它返回一个错误:" GetPageOwner(int 32)没有支持的转换为sql"我究竟做错了什么?如何解决它以获得相同的结果?
return (from page select new Result
{
pageOwner = GetPageOwner(page.page_id)
});
public Post GetPageOwner(int pageid)
{
var posts = (from dp in db.Posts where dp.pageid == pageid select dp);
var returned = posts;
if (posts.Count() > 0)
{
var latest = posts.OrderByDescending(o => o.Date).FirstOrDefault();
var sharedsamedayaslatest = (from p in posts where p.Date.AddDays(1) >= latest.Date select p);
if (sharedsamedayaslatest.Count() > 1)
{
var followedpost = (from p in posts from s in db.Subscriptions where s.Subscriber == UID && s.Subscribedto == p.UserId select p);
var count = followedpost.Count();
if (count == 1)
{
returned = followedpost;
}
else if (count > 1)
{
returned = (from s in followedpost let reposts = GetPostReposts(s.id) let rating = GetPostRating(s.id) let score = reposts + rating orderby score descending select s);
}
else
{
//no follower shared this post so return the most liked
returned = (from s in sharedsamedayaslatest let reposts = GetPostReposts(s.id) let rating = GetPostRating(s.id) let score = reposts + rating orderby score descending select s);
}
}
else
{
//no shares on the day the latest share
returned = sharedsamedayaslatest;
}
}
else
{
//only one post
returned = posts;
}
return returned.FirstOrDefault(); //order by userid gets a random one
}
答案 0 :(得分:3)
Linq to sql必须将.net中的函数转换为sql。并非所有.net函数都在sql中具有等效函数,而且由您编写的函数肯定没有。
话虽如此,您可以将您的函数实现为存储过程,并在您的linq查询中使用它。