linq-if语句或存储过程if语句
本文关键字:语句 if 存储过程 linq-if | 更新日期: 2023-09-27 18:25:13
我想在数据库中运行一段代码。但是,不支持转换为sql(使用linq转换为sql)。
如何在linq中内联或在存储过程中转换此代码逻辑ro?我对数据库和存储过程一无所知,所以我最好用linq写它。
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
}
可能是这样的:
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 = (posts.Where(p => p.Date.AddDays(1) >= latest.Date));
if (sharedsamedayaslatest.Count() > 1)
{
var followedpost = (posts.SelectMany(p => db.Subscriptions, (p, s) => new {p, s}).Where(
@t => s.Subscriber == UID && s.Subscribedto == p.UserId).Select(@t => p));
var count = followedpost.Count();
if (count == 1)
{
returned = followedpost;
}
else if (count > 1)
{
returned = (followedpost.Select(s => new {s, reposts = GetPostReposts(s.id)}).Select(
@t => new {@t, rating = GetPostRating(s.id)}).Select(
@t => new {@t, score = reposts + rating}).OrderByDescending(@t => score).Select(@t => s));
}
else
{
//no follower shared this post so return the most liked
(sharedsamedayaslatest.Select(s => new {s, reposts = GetPostReposts(s.id)}).Select(
@t => new {@t, rating = GetPostRating(s.id)}).Select(
@t => new {@t, score = reposts + rating}).OrderByDescending(@t => score).Select(@t => s)) = returned;
}
}
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
}