我有這Wishlist堂課:
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通過使用以下方法將所有產品添加到表中:
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();
但我得到這個錯誤:
無法創建型別為“Finder.Models.Wishlist”的常量值。在此背景關系中僅支持原始型別或列舉型別。
我究竟做錯了什么?
uj5u.com熱心網友回復:
你能試著像這樣簡化你的查詢嗎:
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();
上面的查詢更加簡單和高效,如果問題仍然存在,可以幫助您更好地了解問題出在哪里。
uj5u.com熱心網友回復:
我認為您不能將串列傳遞WishList給 LINQ。
相反,修改您的 LINQ 查詢,JOIN如下所示:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461436.html
標籤:C# 网 asp.net-mvc 实体框架 林克
