views:

121

answers:

2

Hi!

I'm having a linq to sql schema with a entity "Customers" as well as "Reports". Each customer has zero or more reports.

I want customers to have a LinkedList property, so that i easily can access the next and previous entity for each report.

What would be the best way, if any, to implement this using linq to sql?

Thanks

A: 

All entities created by the Linq to Sql designer (compiled DBML files) are partial classes. So, you can easily add a new class to your solution called Customers like this:

public partial class Customer
{
}

in which you can place a couple public properties

public partial class Customer
{
    public Report Previous {get { /*...*/ } }
    public Report Next {get { /*...*/ } }
}

However, I'd advise against this design. I'd go with whoever is iterating reports to manage what report is next and what report is previous. Another better design would be for the Customer to return a two-way enumerator (my brain is failing me or I'd provide a proper name for the pattern and a link) which you could use to Next or Previous through the collection.

If you still want to do it, you can use Skip() and Take() to manage the current position in the Reports entity collection.

private int _skip = 0;

// in Previous { get {
_skip--;
if(_skip < 0) _skip = 0;
return this.Reports.Skip(_skip).Take(1).FirstOrDefault();

// in Next { get { (not optimized)
_skip++;
if(_skip >= this.Reports.Count()) _skip--;
return this.Reports.Skip(_skip).Take(1).FirstOrDefault();
Will
+1  A: 

You can go on to the design diagram of your Linq to sql clas and right click on the Customer box header and choose Add-> Association . I dialog will appear, and then in their you choose the customer to be the parent class, report to be the child class, choose customerid column on both. Now in the Linq Customer class you can access all the reports that they have. Hope it helpls.

tuanvt