tags:

views:

34

answers:

2

I'm using LINQ and a DataContext to return a collection of objects from a SQL Server table. The table is named "Widgets" and the corresponding C# class I'm using is shown below. The Widgets table contains a Name column, and a TypeID column which is a foreign key to another table of widget types.

[Table(Name = "Widgets")]
public Class Widget
{
    [Column(Name = "Name")]
    public String Name{get;set;}

    [Column(Name = "TypeID")]
    public int TypeID{get;set;}
}

Now I'd much rather be able to access a widget's type by the type name rather then ID as shown below. But the type name comes from another table then the Widget, WidgetTypes.

[Table(Name = "Widgets")]
public Class Widget
{
    [Column(Name = "Name")]
    public String Name{get;set;}

    [Column(Name = "TypeID")]
    public int TypeID{get;set;}

    //NEW PROPERTY
    public String TypeName(get;set;)
}

Is there some way to do a JOIN with a LINQ DataContext that will return data from multiple tables in a database as a single object?


Update:

Here's my DataContext

class WidgetsContext : DataContext
{
    public WidgetsContext(string connection):base(connection)
    {

    }

    public Table<Widget> Widgets;
    public Table<WidgetType> WidgetTypes;
}
A: 

You could create a public partial Class Widget and add the TypeName as a Property of Widget and load the appropriate Type object in the property...

Given you have a correctly configured LINQ Schema, you should have access to this property already...

Alexander
+2  A: 

If you're talking about Linq to SQL, you don't need a join at all in your LINQ code:

var funWidgets = ctx.Widgets.Where(w => w.Type.Name == "FunWidgetType");

(assuming ctx is your DataContext)

All you have to do is make sure you have a relationship defined in your DBML file between Widgets and WidgetTypes.

Dave Markle
Sorry this is the first time I've used LINQ and haven't done anything with a DBML file. Do I need one or is there some way through attributes that I can specify that the values for Widget.TypeName really come from the WidgetTypes table? I also added the code for my DataContext to the question.
Eric Anastas
I'm sure you can do LINQ without a DBML file. But it's a *world of pain*. If I were you, I would stop right now, add the DBML file through Visual Studio, remove the classes you've made, and re-generate the model by dragging and dropping the tables from your database onto the DBML file.
Dave Markle