tags:

views:

76

answers:

3

1) I wish to clarify some doubts on collections.

SampleDBDataContext PersonDB = new SampleDBDataContext("");
Table<Person> p=PersonDB.GetTable<Person>();
IEnumerable<Person> per = PersonDB.GetTable<Person>();
IQueryable<Person> qry = PersonDB.Persons.Select(c => c);

what are the differences between using Table<Person>,IEnumerable<Person>,IQueryable<Person>.Any specific need to choose the particular one?

2) For Adding records Add() method not appears in my IDE,(i.e) PersonDB.Persons.Add(). What is the problem here?

+6  A: 

1.

  • IEnumerable<> is an interface that applies to any collection whose members can be enumerated or iterated over.

  • IQueryable<> is a LINQ interface that applies to any collection whose members can be lazily queried. (queried without materializing the result set until its members are accessed)

  • Table<> is a class that I've not used before but "represents a table for a particular type in the underlying database."

Which one you choose depends on what your needs are, but IEnumerable<> is the most general, so I would use that in my type declarations if it's sufficient.

2.

To insert a person use InsertOnSubmit():

Person person = new Person() { ... };
PersonDB.Persons.InsertOnSubmit(person);
PersonDB.SubmitChanges();
recursive
A: 

Table<> is well, a table. It can return IQueryable results and can perform inserts/other database specific operations. It is linked to a DataContext.

IQueryable<> is a list that is well, not a list. Basically IQueryable doesn't actually load any data until you actually request it (late execution). As a result you can perform multiple operations before the whole thing is sent to the database. Think of IQueryable<> as an SQL statement in progress, rather then the actual results.

IEnumerable<> is just a standard interface for any list of objects that can be enumerated. When an IQueryable actually executes, you get an IEnumerable set to go through.

Add appears for indvidual instances - for example Person.Add(). For raw tables you should use the Insert* methods.

David
+1  A: 

Table(T) is the class that LINQ to SQL uses for query results from a table; it is also used for properties of the data context, so that you can use the data context properties in your queries. So the code in your post is duplicating some code that LINQ is already doing for you. PersonDB.Persons should always be sufficient for querying persons.

For results, you will likely want a collection, so while IEnumerable and IQueryable are fine, you can also consider using a list:

List<Persons> pers = PersonDB.Persons.Where(p => p.name == aName).ToList();

Note that this is an immediate execution, not a lazy (deferred) execution. ToList() forces immediate query execution.

Cylon Cat