ASP.NET MVC - Select 来自两个表然后比较

ASP.NET MVC - Select from two tables then compare

我有这个 Wishlist class:

public class Wishlist
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
    public string PersonId { get; set;}
    [ForeignKey("PersonId")]
    public virtual ApplicationUser Person { get; set; }
}
public class Product
{
    public string Title { get; set; }
    public int CategoryId { get; set; }
    [ForeignKey("CategoryId")]
    public virtual Category Category { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public bool Featured { get; set; }
    public bool Sold { get; set; }
    public string Image { get; set; }
    [NotMapped]
    public HttpPostedFileBase UploadImage { get; set; }
    public string PersonId { get; set; }
    [ForeignKey("PersonId")]
    public virtual ApplicationUser Person { get; set; }
}

我正在尝试将所有产品添加到 dbcontext.Wishlist table,方法是:

string currentUserId = User.Identity.GetUserId();
var list2 = DbContext.Wishlist.Where(p => p.PersonId == currentUserId).ToList();
var list3 = (from p in DbContext.Products
             from w in list2
             where p.PersonId == w.PersonId
             select new Models.Response.ProductIndexResponse()
             {
               Id = p.Id,
               Image = p.Image,
               Title = p.Title,
               Price = p.Price
             }).ToList();

但是我得到这个错误:

Unable to create a constant value of type 'Finder.Models.Wishlist'. Only primitive types or enumeration types are supported in this context.'

我做错了什么?

我认为您不能将 WishList 的列表传递给 LINQ。

而是使用 JOIN 修改您的 LINQ 查询,如下所示:

var query = (from p in DbContext.Products
             join w in DbContext.Wishlist on p.PersonId equals w.PersonId
             where p.PersonId == currentUserId
             select new
             {
               Id = p.Id,
               Image = p.Image,
               Title = p.Title,
               Price = p.Price
             }).ToList();

var result = query
    .Select(x => Models.Response.ProductIndexResponse()
    {
        Id = x.Id,
        Image = x.Image,
        Title = x.Title,
        Price = x.Price
    })
    .ToList();

你能尝试像这样简化你的查询吗:

var wishPorducts = DbContext.Wishlist
    .Where(p => p.PersonId == currentUserId)
    .Select(x => new Models.Response.ProductIndexResponse()
         {
           Id = x.Product.Id,
           Image = x.Product.Image,
           Title = x.Product.Title,
           Price = x.Product.Price
         })
     .ToList();

上面的查询更简单高效,如果问题仍然存在,可以帮助您更好地了解问题出在哪里。