views:

41

answers:

3

Hello!

I use linq2sql and m_DateContext.Dates class for table

ID | ParentID | Datestamp
---|----------|----------
1  | NULL     | 1.8.2010
---|----------|----------
2  | 1        | 2.8.2010
---|----------|----------
3  | 1        | 4.8.2010

etc...

I need to write the linq query to select only rows where ParentID is NULL (ex: ID=1), BUT Value of DATESTAMP must be equals to max date from it's child rows. (Row ID=3).

Linq query must return an instance of m_DateContext.Dates with non-broken links to entities in database schema.

Result must be smthng like:

ID = 1 ParentID=NULL Datestamp = 4.8.2010

Please help

+1  A: 

All kinds of assumptions (linq to entities or sql) and I think you want a let...

var query = (
     from i in TDates
        where i.ParentID==null
     let maxDate= TDates.Max(d=>d.Datestamp) 
     select new {
       NonBrokenRecord = i,
       Datestamp = maxDate
     }

).ToList();

Once you get the results you could do...

query.ForEach(x=>x.NonBrokenRecord.DateStamp = x.Datestamp);
query = query.Select(x=>x.NonBrokenRecord).ToList();
Nix
OK, but in your example i loose connections between all linket entities in database schema - Dtable.OtherEntity.FieldValue
Maxim
Well, you need to add this to your question. Please elaborate on what you mean.
Nix
If I follow that right, Datestamp will be the highest datestamp overall, not the highest where child.ParentId = parentid
James Curran
I think i fixed for what he wanted... this seems wrong...
Nix
+1  A: 
var query = 
    from p in TDates 
    where p.ParentID==null 
    select new TDate 
    { 
        ID = p.ID, 
        ParentID = null, 
        Datestamp = TDates.Where(c=> c.ParentID == p.ID).Max(c=>c.Datestamp)
    };
James Curran
This is what i dont get, ParentID will always be null? So your datestamp code would always return the max of all null parentids?
Nix
@Nix: This table (I assume) has a foriegn key relationship into itself where child.ParentID == Parent.ID. Now, plot your query as if they were two separate tables. So, ParentID is always null on parent records, but it's not null on the Parent's children's records.
James Curran
What i was trying to say is your clause .Where(c=> c.ParentID == p.ID) conflicts with p.ParentID==null you will always have .Where(c=> c.ParentID==null)
Nix
@Nix: No conflict. Remember, I said, pretent it's two separate tables. The Datestamp uses a separate query with the only connection to the outer query being p.ID.
James Curran
+2  A: 
var rows =
(
from parent in db.Dates
where parentId == null
let MaxDate = parent.Dates.Max(child => child.DateStamp)
select new{DateObject = parent, MaxDate = MaxDate}
)

List<Date> result = new List<Date>();
foreach(var row in rows)
{
  Date d = row.DateObject;
  d.DateStamp = row.MaxDate;
  result.Add(d)
}
David B