Asp.Net Entity Framework to select and display record in GridView
.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridViewCS" CssClass="Grid" runat="server" AutoGenerateColumns="false"
PageSize="10" AllowPaging="true" DataSourceID="dsCustomers">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="dsCustomers" runat="server" EnablePaging="true" SelectMethod="GetCustomers"
SelectCountMethod="GetCustomersCount" TypeName="CustomerDataSource" MaximumRowsParameterName="maxRows"
StartRowIndexParameterName="startIndex"></asp:ObjectDataSource>
</form>
</body>
</html>
Inside App_Code Create entity framework .edmx file name Customer:-
CustomerDataSource.cs
Customers.Designer.cs
Customers.edmx
--------------------------------------------
CustomerDataSource.cs
using System;
using System.Web;
using System.Linq;
using NorthwindModel;
using System.Collections.Generic;
public class CustomerDS
{
public List<Customer> GetCustomers(int startIndex, int maxRows)
{
using (NorthwindEntities entities = new NorthwindEntities())
{
return (from customer in entities.Customers
select customer)
.OrderBy(customer => customer.CustomerID)
.Skip(startIndex)
.Take(maxRows).ToList();
}
}
public int GetCustomersCount()
{
using (NorthwindEntities entities = new NorthwindEntities())
{
return entities.Customers.Count();
}
}
}
using System.Web;
using System.Linq;
using NorthwindModel;
using System.Collections.Generic;
public class CustomerDS
{
public List<Customer> GetCustomers(int startIndex, int maxRows)
{
using (NorthwindEntities entities = new NorthwindEntities())
{
return (from customer in entities.Customers
select customer)
.OrderBy(customer => customer.CustomerID)
.Skip(startIndex)
.Take(maxRows).ToList();
}
}
public int GetCustomersCount()
{
using (NorthwindEntities entities = new NorthwindEntities())
{
return entities.Customers.Count();
}
}
}
Important in customer.designer.cs that is auto generated file
public partial class NorthwindEntities : ObjectContext
{
public NorthwindEntities() : base("name=NorthwindEntities", "NorthwindEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
}
{
public NorthwindEntities() : base("name=NorthwindEntities", "NorthwindEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
}