猿问

检索复合键表数据的 Linq 查询不成功

我想编写一个 linq 查询来检索由多对多关系生成的复合表的所有数据。


这是我在控制器中的查询


 public ActionResult Index()

    {

        var act = (from i in _context.act

                   from j in _context.mvz

                   where i.Id == j.Id

                   select i).ToList();



        var mvz = _context.mvz.ToList();

        var vm = new AAMMViewModel()

        {

            actz = act

            mvz = mvz

        };

        if (vm == null)

        {

            return Content("No items found in database");

        }

        return View(vm);

    }

这是视图模型


  public class AAMMViewModel

{

    public List<Actors> actz { get; set; }

    public List<Movies> mvz { get; set; }

    public AAMMViewModel()

    {

        actz = new List<Actors>();

        mvz = new List<Movies>();

    }

}

它没有给出想要的结果,我知道我的 Linq 查询的逻辑有问题。如果有人有这方面的专业知识,请指导我。


人到中年有点甜
浏览 162回答 2
2回答

繁花不似锦

你可以这样做:var act =&nbsp;&nbsp; &nbsp; (from i in _context.act&nbsp; &nbsp; where i.Id.SelectMany(id => _context.mvz.Contains(id.Id))&nbsp; &nbsp; select i).ToList();

森林海

你确定演员和电影的ID是一样的吗?如果是,请进行连接并使用正确的属性名称。您在 linq 中使用 act 代替 actzpublic class AAMMViewModel{&nbsp; &nbsp; public List<Actors> actz { get; set; }&nbsp; &nbsp; public List<Movies> mvz { get; set; }&nbsp; &nbsp; public AAMMViewModel()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; actz = new List<Actors>();&nbsp; &nbsp; &nbsp; &nbsp; mvz = new List<Movies>();&nbsp; &nbsp; }}var act = (from i in _context.actz&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;join j in _context.mvz ON i.Id == j.Id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select i).ToList();
随时随地看视频慕课网APP
我要回答