I’m pretty new to LINQ to SQL, and until recently have had no problems. Writing in C#.
I’ve got a model helper .cs file. I am attempting to create a public list that I can base a view off of.
Here’s the code in the model helper (with extraneous, working, content removed:
using System;
using System.Collections.Generic;
using System.Linq;
namespace sample_runs.Models {
partial public class SampleRunsDataContext {
public List<attendee> GetMyRuns(int me) {
var mine = (from a in attendees
join s in sample_runs
on a.sample_run_id equals s.sample_run_id
where a.user_id == me
orderby a.sample_run_id descending
select new {
s.sample_run_id,
a.role.role_name,
s.sample_run_status.sample_run_status_name,
s.project_number,
s.run_type.run_type_name,
s.description
}).ToList();
return mine;
}
}
}
As for the database, consider the two tables involved like this. sample_runs is like a list of parties or events. So, for each line we’ve got all the information for the party. Then, we’ve got a table called attendees, where all the party attendees are listed individually. Each line has information about attendees, including their ‘role’ which is where I suppose the metaphor breaks down. There could be any number of attendees for each party. The database is pretty with foreign keys and your usual variety of normalization.
All I want is, for a given attendee, a list of all the parties they’ve been to. I hope that makes sense.
All my other linq statements and lists in this file are working fine. This one gives me this brand of grief:
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>'
to 'System.C9ollections.Generic.List<sample_runs.Models.attendee>
I’m confused about whether this should be a public list or something else.
I’m unsure whether
List<attendee>
should really be
List<attendee>
due to the join.
After some research, I’ve played with what the ‘mine’ variable gets sent to, and whether this should be a List<> or IENumerable<> etc etc etc. I am woefully lost.
Just for reference, this is what I want to do with ‘GetMyRuns’, in the controller:
public ActionResult myruns() {
return View(db.GetMyRuns(someintvar));
}
And then I figure I’ll build a strongly-typed view and go from there.
I know this may be a softball question, but I’m incredibly grateful for any help you may be able to offer me.
Thank you.
As the error indicates,
mineis a list of annonymous objects, while you should be returning a list ofattendeeobjects. Theselectin your query creates the annonymous object (note the absence of any type indication):The solution to your problem would depend on how exactly your application is structured, but one way to fix it would be by creating some kind of DTO (Data Transfer Object) list and returning it instead:
Your
AttendeeDtoclass would look like this:And BTW – I hope you never actually name integer variables
meand List variablesminein production code? 😉