user3297426
user3297426

Reputation:

Linq to SQL GetTable

I am trying to retrieve whole table from database into my Data Grid View. I have find this article but in my Windows Form project doesn't exist var q = from a in emp.GetTable<Employee>() select a; Here I have an error

Error 1 'EmployeeList.EmployeeEntities1' does not contain a definition for 'GetTable' and no extension method 'GetTable' accepting a first argument of type 'EmployeeList.EmployeeEntities1' could be found (are you missing a using directive or an assembly reference?)

How can I fix it?

I have already added using System.Data.Linq; but nothing has changed..

Is there any other way to retrieve whole table into my Data Grid View? Or how can I improve it

Upvotes: 0

Views: 6891

Answers (1)

Barry West
Barry West

Reputation: 552

Just looking at the error emp should inherit from DataContext in the class definition. DataContext has the GetTable Method.

Here is a link that should help you out.

http://msdn.microsoft.com/en-us/library/bb399375(v=vs.110).aspx

// DataContext takes a connection string. 
DataContext db = new DataContext(@"c:\Northwnd.mdf");

// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();

// Query for customers from London. 
var query =
    from cust in Customers
    where cust.City == "London" 
    select cust;

foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);

A model using a class that inherits from DataContext

public partial class Northwind : DataContext
{
    public Table<Customer> Customers;
    public Table<Order> Orders;
    public Northwind(string connection) : base(connection) { }
}

Then in your Controller.

Northwnd db = new Northwnd(@"c:\Northwnd.mdf");
var query =
    from cust in db.Customers
    where cust.City == "London" 
    select cust;
foreach (var cust in query)
    Console.WriteLine("id = {0}, City = {1}", cust.CustomerID,
        cust.City);

Upvotes: 1

Related Questions