Reputation: 6196
i am working on asp.net mvc3. i am using database designed in sql server. i have added my database in App_Data using Ado.connection.
This is my table:
I want to access Code where ID=2
I am using this query:
ViewBag.pc = db.Product.Where(r => r.ID == p);
but this returns whole row. So what should i do to select particular column(here code). Please help me.
Upvotes: 1
Views: 2128
Reputation: 9
Your query is assigning the ViewBag.pc
variable with a Product
object. This means that ViewBag.pc
object will have properties for each column in the table.
So, to refer to the data stored in the Code
column in your view, you would use something like this:
<%: ViewBag.pc.Code %>
Upvotes: 0
Reputation: 108967
var code = db.Product.Where(r => r.ID == 2).Single().Code
should work.
If there could be more than one row (or none), you can use FirstOrDefault()
var row = db.Product.Where(r => r.ID == 2).FirstOrDefault();
if(row != null)
{
var code = row.Code;
}
If there can only be one(or none), you can replace FirstOrDefault()
with SingleOrDefault()
above.
Upvotes: 2