Wednesday, 15 May 2013

c# - Linq query to select an item, with a parameter in a collection -



c# - Linq query to select an item, with a parameter in a collection -

i'm struggling linq query working within asp.net querystring method. i've tried various things, still not quite getting right.

my model is:

public class sporttype { public int sporttypeid {get; set;} public string sporttypename {get; set;} } public class company { public int companyid {get; set;} public string name {get; set;} public icollection<sporttype> sporttypes {get; set;} }

there sport type table in database values such (1=football, 2=golf, 3=cricket) etc.

a company can have none/one/more 1 sport type. want select companies specific sport type.

but linq query gives compiler error:

argument 1: cannot convert system.linq.iqueryable mynamespace.sporttype

public iqueryable<company> getcompanies([querystring("sporttypeid")] int? sporttypeid) { var db = new mydatabasecontext(); iqueryable<company>query = db.companies; if (sporttypeid.hasvalue && sporttypeid>0) { query = query.where(thecompany => thecompany.sporttypes.contains(db.sporttypes.select(sp => sp.sporttypeid == sporttypeid))); } homecoming query; }

can help? thanks.

you having error due homecoming value of

db.sporttypes.select(sp => sp.sporttypeid == sporttypeid)

line. returns collection(with, probably, many values) of sporttype instances while contains method expects single sportytype instance. seek this:

public iqueryable<company> getcompanies([querystring("sporttypeid")] int sporttypeid) { var db = new mydatabasecontext(); iqueryable<company>query = db.companies; if (sporttypeid.hasvalue && sporttypeid>0) { query = query.where(thecompany => thecompany.sporttypes.any(stype => stype.sporttypeid == sporttypeid))); } homecoming query; }

c# asp.net linq

No comments:

Post a Comment