【问题标题】:How do I convert this SQL to Linq? [duplicate]如何将此 SQL 转换为 Linq? [复制]
【发布时间】:2021-04-10 13:17:32
【问题描述】:

这个 SQL 在 Linq 中会是什么样子?

你可以看到我要使用的 SQL 语句,我对 Linq 还很陌生:

SELECT user_id
FROM profiles
LEFT JOIN interests ON profiles.id = interests.profile_id
WHERE interest IN ('Shopping', 'Art') 
  AND Sex IN ('Man', 'Woman') 
  AND user_id NOT IN (SELECT user_1 FROM matches) 
  AND user_id != 84
GROUP BY user_id
ORDER BY COUNT(user_id) DESC;

下面你可以看到不同的模型,所有的模型都有一个来自modelbase的id

轮廓模型:

namespace Sparks.Presentation.Entities
{
    public partial class Profile: ModelBase
    {
        public Profile()
        {
            Interests = new HashSet<Interest>();
        }

        public int UserId { get; set; }
        public string Name { get; set; }
        public string Picture { get; set; }
        public string Birthdate { get; set; }
        public string Sex { get; set; }
        public string Orientation { get; set; }

        public virtual User User { get; set; }
        public virtual ICollection<Interest> Interests { get; set; }

        [NotMapped]
        public IFormFile FormFile { set; get; }
    }
}

兴趣模型:

namespace Sparks.Presentation.Entities
{
    public partial class Interest: ModelBase
    {
        public int ProfileId { get; set; }
        public string InterestName { get; set; }

        public virtual Profile Profile { get; set; }
    }
}

匹配模型:

namespace Sparks.Presentation.Entities
{
    public partial class Match: ModelBase
    {
        public Match()
        {
            Chats = new HashSet<Chat>();
        }

        public int User1 { get; set; }
        public int User2 { get; set; }
        public bool Matchstatus { get; set; }
        public bool Matchmade { get; set; }
        public DateTime CreatedOn { get; set; }

        public virtual User User1Navigation { get; set; }
        public virtual User User2Navigation { get; set; }
        public virtual ICollection<Chat> Chats { get; set; }
    }
}

希望有人能帮帮我吗?

【问题讨论】:

  • 也许我的SQL to LINQ Recipe 可以帮助你。
  • 你用的是什么ORM工具?
  • “我怎样才能让这个工作代码变得更慢更难维护?”这实际上是同一个问题;)

标签: c# sql linq


【解决方案1】:

这更接近于预期的查询。看起来与 SQL 类似,但 select 部分是最后一条语句。

var interestFilter = new [] {"Shopping", "Art"};
var sexFilter = new [] {"Man", "Woman"};

var query = 
  from p in ctx.Profiles
  from i in p.Interests
  where interestFilter.Contains(i.InterestName) && sexFilter.Contains(p.Sex)
    && !ctx.Matches.Any(m => m.User1 == u.UserId)
    && p.UserId != 84
  group p by p.UserId into g
  order by g.Count()
  select g.Key;

var result = query.ToList();

【讨论】:

  • 你也有它作为 lambda 表达式吗?
  • 不要问我这个;)我讨厌此类查询中的 lambda 语法,甚至不推荐。 ReSharper 可以通过单击将此查询转换为 lambda 表达式。
猜你喜欢
  • 2015-10-02
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 2012-08-20
  • 2016-08-07
  • 2016-01-23
  • 2022-01-22
相关资源
最近更新 更多