views:

25

answers:

1

Hi, I'm new to ASP.NET, C# and the MVC framework but have managed to build a site that works pretty well.

Now I am trying to create a reporting section for the site to display a table of information on all users and just can't get my head around creating custom model classes for the joined table data. I have seen lots of examples with one record but none with a full data set.

I am using the Entity framework and pulling my data out with:

var usersInfo = from c in _dataModel.UserProfile select new { c.Forname, c.Surname, c.aspnet_Users.UserName, c.Countries.CountryName, c.Specialities.SpecialityName};

The data returns fine, but it is of the type: 'System.Data.Objects.ObjectQuery1[<>f__AnonymousType65[System.String,System.String,System.String,System.String,System.String]]'

How would I get this into a type that I can pass back to a strongly typed View?

Thanks,

Giles

+3  A: 

Make a named class to hold the data that is currently encapsulated in the anonymous data you have selected:

public class MyClass
{
    public string Forename{get;set;}
    public string Surname{get;set;}
    //etc
}

var usersInfo = from c in _dataModel.UserProfile select new MyClass{ Forename=c.Forname, Surname=c.Surname, ...};

Now you've got a concrete type that you can throw around your app with ease. If you run into this a lot, refactoring tools such as Resharper can convert from anonymous to named types in a couple of clicks.

spender
Thanks, but I'm getting errors in VS on the select that "Cannot convert lambda expression to type 'string' because it is not a delegate type" and on my "{" because MyClass doesn't implement IEnumerable. Any Ideas what I'm doing wrong?
Giles
It's not possible to tell you with such little info. Your ViewPage is of which type? Assuming usersInfo will be the model, it should be IEnumerable<MyClass>. If problems persist then you'll have to state them more clearly.
spender
They are build errors on the Controller rather than runtime View errors. Error 1 - Cannot convert lambda expression to type 'string' because it is not a delegate type. Error 2 - Cannot initialize type 'HAE.Models.MyClass' with a collection initializer because it does not implement 'System.Collections.IEnumerable'. I'm not even trying to push it to the View yet.
Giles
I've updated my code. Should eliminate the 2nd error. Any closer?
spender
I think I just had the "ahhhaaaaa" moment I was looking for! Both errors gone and a working View. Thanks very much, Giles.
Giles