Reputation: 675
I am using EF 4.x to populate an ASP.NET dropdown list. I first create a variable:
CPAS_EM.qryxrefVendorWorker wrkrs;
Then, I go to populate it:
using (CPASEntities sds = new CPASEntities())
{
wrkrs = (qryxrefVendorWorker)
(from w in sds.qryxrefVendorWorkers
where w.VendorID == currVendorID &&
((w.ExpiryDate == null) | (w.ExpiryDate >= currWorkDate))
select w);
ddlWorker.DataSource = wrkrs;
ddlWorker.DataValueField = wrkrs.WorkerID.ToString();
ddlWorker.DataTextField = wrkrs.WorkerName;
ddlWorker.DataBind();
}
I'm getting an error on the "wrkrs = ..." statement indicating a casting error:
System.InvalidCastException was unhandled by user code
Message=Unable to cast object of type 'System.Data.Objects.ObjectQuery`1[CPAS_EM.qryxrefVendorWorker]' to type 'CPAS_EM.qryxrefVendorWorker'
Can anyone point me in the right direction here?
Upvotes: 0
Views: 84
Reputation: 1166
You can try this:
List<sds.qryxrefVendorWorkers > lstWorkers =
(from w in sds.qryxrefVendorWorkers
where w.VendorID == currVendorID &&
((w.ExpiryDate == null) | (w.ExpiryDate >= currWorkDate))
select w).ToList();
ddlWorker.DataSource = lstWorkers;
ddlWorker.DataValueField = "WorkerID";
ddlWorker.DataTextField = "WorkerName";
ddlWorker.DataBind();
This will return a set of qryxrefVendorWorkers
.
The casting failed because (in simple terms) you tried to cast a set of objects into a single object when you cast the query into a qryxrefVendorWorker
Upvotes: 0
Reputation: 7484
Why do you need the variable declared outside of the using scope? Can't you do:
using (CPASEntities sds = new CPASEntities())
{
var wrkrs = (from w in sds.qryxrefVendorWorkers
where w.VendorID == currVendorID
&& ((w.ExpiryDate == null) | (w.ExpiryDate >= currWorkDate))
select w).FirstOrDefault();
ddlWorker.DataSource = wrkrs;
ddlWorker.DataValueField = wrkrs.WorkerID.ToString();
ddlWorker.DataTextField = wrkrs.WorkerName;
ddlWorker.DataBind();
}
and eliminate the declaration altogether?
Also, as user1908061 said, you also need the FirstOrDefault() to get just a single object instead of a collection.
Upvotes: 0
Reputation: 626
Your code
(from w in sds.qryxrefVendorWorkers
where w.VendorID == currVendorID && ((w.ExpiryDate == null) | (w.ExpiryDate >= currWorkDate))
select w)
is actually a query, not a single object. You probably want to add FirstOrDefault()
to just get a single element. Then there's also no cast necessary.
Upvotes: 4