0

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();
}
1
  • You need to make a ViewModel class with properties you want, then continue your query with .Select(x=> new Vm(){...}).ToList() Commented Apr 16, 2016 at 8:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.