loviji
loviji

Reputation: 13080

LINQ expression result implicit to inherited object

I've an Document object and User object, generated by Entity Framework Model Generator.

I want to get Document list, plus userCount created according to this Document.

So, I've created new object DocumentWithUserCount:

public class DocumentWithUserCount:Document
{
    public uAmount {get;set}
}

And LINQ to retain data (below code, I need your help) :

    var ed = (from d in _entity.Document
     join p in _entity.User[get DocID and count by this docID ] on d.RID equals p.DocID         
select new DocumentWithUserCount(xxxx)).ToList();

How to do this?

EDIT: Simply I want to do equivalent code below with LINQ.

    SELECT d.*, p.* from Document d INNER JOIN (select docid, count(RID) as uAmount from User
    GROUP BY DocID) p ON d.RID=p.docid

Upvotes: 1

Views: 193

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273264

I think that inheritance is the wrong tool here. Use composition instead. And It's not clear if you even nneed the Join, there should be a navigation property:

var eds = from d in _entity.Document       
   select new { Document=d, UserCount=d.Users.Count() };  // anon type

or

public class DocumentWithUserCount  //:Document
{
    public Doucument { get; set; }
    public int Amount {get;set}
}
var eds = from d in _entity.Document       
   select new DocumentWithUserCount { Document=d, Amount=d.Users.Count() };

Upvotes: 1

M Afifi
M Afifi

Reputation: 4795

Does this not work?

var documentWithUserCount =
    from Document d in _entity.Document
    join p in _entity.User on d.RID equals p.DocID
    select new DocumentWithUserCount(d, p.Count());

Add a constructor in DocumentWithUserCount as follows

public DocumentWithUserCount(Document doc, int count) : base(d)
{
    uAmount = count;
}

Add a constructor in Document that will take a Document and set the appropriate properties.

Upvotes: 1

Related Questions