Kabi
Kabi

Reputation: 2045

reading the result of LINQ query using Datarow

How can I read the reult of LINQ query row by row .(Is it possible)? I want to implemente this one but doesn't possible:

aspnetdbDataContext aspdb = new aspnetdbDataContext();
var res = from r in aspdb.RouteLinqs
          where r.UserId == userId
          select r;

foreach (DataRow row in res)
{
    // ...

An exception is thrown:

Cannot convert type 'QuickRoutes.DAL.RouteLinq' to 'System.Data.DataRow'

Edit:

in the foreach block I have:

foreach (var row in res)
{
    var routeId = (int)row["RouteId"];
    var route = new Route(routeId)
                {
                    Name = (string)row["SourceName"],
                    Time = row["CreationTime"] is DBNull ? new DateTime() :
                                    Convert.ToDateTime(row["CreationTime"])
                };

    route.TrackPoints = GetTrackPointsForRoute(routeId);
    result.Add(route);
}

If I use var this error in some lines occure:

Cannot apply indexing with [] to an expression of type 'QuickRoutes.DAL.RouteLinq'

Upvotes: 2

Views: 1967

Answers (2)

HatSoft
HatSoft

Reputation: 11191

Try this

foreach (var row in res)
{.....

Update : I would like to give you smaller syntax, hope you don't mind

foreach(var routeLinq in aspdb.RouteLinqs.Where(rl => rl.UserId == userId) )
{
    int routeId = routeLinq.RouteId;
}

Upvotes: 1

Philip Daubmeier
Philip Daubmeier

Reputation: 14934

use

foreach (RouteLinq row in res)
{
    // ...

or simply:

foreach (var row in res)
{
    // ...

Your Linq query doesnt return a collection of DataRow objects, but instead objects of a class that was autogenerated from your database table name.

Edit, to account for the edit in your question:

Why are you accessing the members of your objects like they are still DataRow objects?

You want to access it like:

int routeId = row.RouteId;

I really recommend you to look at a few basic Linq-to-SQL (or ORM in general) tutorials.

Upvotes: 1

Related Questions