Muhammad Ibrar
Muhammad Ibrar

Reputation: 79

How to select specific columns in Entity Framework in ASP.NET WebForms?

I want to select specific columns like username, message and subject only from SQL Server Database in Entity Framework in ASP.NET. But my program returns all the columns from table emailtable.

Here is my code:

kicsEntities db = new kicsEntities();

protected void Page_Load(object sender, EventArgs e)
{
    emailtable et = new emailtable();

    string var = Session["username"].ToString();

    GridView1.DataSource = db.emailtables.Where(em => em.receiver == var).ToList(); 
    GridView1.DataBind();
}

Upvotes: 0

Views: 1088

Answers (2)

You can use projection. For example, create a view model (c# class) called MyClass and declare the properties you require from the database object.

public class MyClass
{
    public string Username { get; set; }
    public string Message { get; set; }
    public string Subject { get; set; }
}

Now using Linq you can request only the properties you require from the database table

db.TableName.Select(m => new MyClass 
{
    Username = m.Username,
    Message = m.Message,
    Subject = m.Subject
});

You can now bind the returned collection as your gridview's datasource with the added benefit of having a strongly typed control.

Upvotes: 2

Wicher Visser
Wicher Visser

Reputation: 1543

You could add a view to your database model and have it included only those columns that you would want to retrieve. If your approach is code-first, you can add/map the view as described in this SO post.

Upvotes: 0

Related Questions