Reputation: 2295
I am trying to add filter by ID for the following:
public ActionResult Index()
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
What I would like to do is the following:
public ActionResult Index(long? id)
{
if (id != null)
{
var model = from o in new MainDBContext().OffLinePayments
**Where Assigned_ID == id**
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
else
{
var model = from o in new MainDBContext().OffLinePayments
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
return View(model);
}
}
Upvotes: 3
Views: 2891
Reputation: 13366
A cleaner, shorter and much more readable syntax would look like this:
public ActionResult Index(long? id){
using (var ctx = new MainDBContext())
{
var entities = ctx.OfflinePayments.Where(e => !e.HasValue || e.Assigned_ID == id.Value);
var model = entities.Select(e => new EditOfflinePayment { ID = e.ID, Amount = e.Amount }).ToList();
return View(model);
}
}
Upvotes: 0
Reputation: 437376
If I understand correctly, your problem is that the compiler doesn't let you write where o.Assigned_ID == id
in the query.
That's because id
is a Nullable<long>
, which is not implicitly convertible to a long
(which OffLinePayment.Assigned_ID
presumably is).
You need to write where o.Assigned_ID == id.Value
instead. Take a look at what the Value
property does so that you don't get any surprises.
Upvotes: 0
Reputation: 70369
try
var model = from o in new MainDBContext().OffLinePayments
where o.Assigned_ID == id
select new EditOffLinePayment
{
ID = o.ID,
Amount = o.Amount
};
Upvotes: 2