I am not sure why the following does not return a value for Vend as a string .
When I check for the value of vend it says: System.Data.Objects.ObjectQuery``1[System.String]
string vend = (from vnd in db.Vendors
where vnd.VendorID == id
select vnd.VendorName).ToString();
When I view the value of vend, it is not what I expected
You are getting an IQueryable<String>
back from you query. You need either the First or Single or something:
string vend = (from vnd in db.Vendors
where vnd.VendorID == id
select vnd.VendorName).First().ToString();
The ToString
is not need if VendorName
is a String.
string vend = db.Vendors.Single(vnd => vnd.VendorID == id); // more terse
First will grab the first record from the set and will throw an exception if the set is empty.
FirstOrDefault will return the first record or the default for the type expected, no exception.
Single will return the first record of the set, but will throw an exception if there is more than one record in the set or if the set is empty.
SingleOrDefault will return the first record of the set or the default for the type if empty, but will throw an exception if there are more than one record in the set.
You are calling ToString() on the query itself, not on the result of your query. Try
string vend = (from vnd in db.Vendors
where vnd.VendorID == id
select vnd.VendorName).First();
This gets the first result of the query, which should already be a string (assuming VendorName is a string). Thus, no need to call ToString().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With