Reputation: 7818
I'm just drawing a blank here.
The error I get on the "purchases = purchases.Where" line is:
Cannot implicitly convert type 'System.Linq.IQueryable<WWLTracker.Models.StockPurchase>' to 'System.Data.Entity.DbSet<WWLTracker.Models.StockPurchase>'. An explicit conversion exists (are you missing a cast?)
My domain model/class is:
public class StockPurchase
{
public int StockPurchaseId { get; set; }
[Required]
[Display(Name = "Date of purchase")]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Required]
public double Amount { get; set; }
}
Controller:
// GET: /Popular/
public ActionResult Index(DateTime? From, DateTime? To)
{
var purchases = db.StockPurchases;
if (From != null && To != null)
{
purchases = purchases.Where(x => x.Date >= From && x.Date <= To);
}
Return View(purchases.ToList());
}
I know this is something simple - can anyone please advise what I'm missing?
Thank you,
Mark
Upvotes: 1
Views: 2929
Reputation: 2178
Here you are assigning DbSet of Purchases to variable purchases
var purchases = db.StockPurchases;
and then you are trying to assign it the result of where clause which is IQeuryable, So it could not convert IQueryable to DbSet that's why you are getting exception.
Change it this way :
public ActionResult Index(DateTime? From, DateTime? To)
{
List<StockPurchase> purchases = new List<StockPurchase>();
if (From != null && To != null)
{
purchases = db.StockPurchases.Where(x => x.Date >= From && x.Date <= To).ToList();
}
else
{
purchases = db.StockPurchases.ToList();
}
Return View(purchases.ToList());
}
Upvotes: 1
Reputation: 223187
Your purchases is of type DBSet
and later you are trying to assigning it your query an IQueryable<T>
. It appears that you want to return a filtered list if your parameters has a value, otherwise you want to return the complete list. You can do that as:
// GET: /Popular/
public ActionResult Index(DateTime? From, DateTime? To)
{
if (From != null && To != null)
{
return View(db.StockPurchases.Where(x => x.Date >= From && x.Date <= To).ToList());
}
else
{
return return View(db.StockPurchases.ToList());
}
}
Upvotes: 1
Reputation: 156918
The type of purchases
is inferred from the property db.StockPurchases
which is DbSet. (so the type of purchases
will become DbSet<WWLTracker.Models.StockPurchase>
. You can't just convert that later to IQueryable<WWLTracker.Models.StockPurchase>
.
You should check the shared type between the two results which is System.Linq.IQueryable<WWLTracker.Models.StockPurchase>
and set the type of purchases
to that.
Try this:
IQueryable<WWLTracker.Models.StockPurchase> purchases = db.StockPurchases;
...
Upvotes: 3