c# - how to execute a linq query in association table -
i'm new entity framework.
i have 3 tables.
candidats : id,cin poste : id postecandidats : candidat_id, poste_id
i want candidat has (cin= 'abc15' , poste_id = 3)
my models :
public class candidat { public int id { set; get; } public string num_cin { set; get; } public icollection<poste> postes { get; set; } } public class poste { public int id { set; get; } public string poste_name {set;get} public list<candidat> candidats {set;get;} }
that generates association table postecandidats.
i tried :
i tried gives me error
var v = _db.candidats .where(c => c.num_cin == "abc15" && c.postes.any(pc => pc.id == 3)); var candi = v.singleordefault();
but gives me nothing
(i think problem any() method )
2 samples both work:
var lcandidat = new list<candidat>(); lcandidat.add(new candidat{ id = 2, num_cin = "xabc", postes = new collection<poste>() { new poste {id = 10, poste_name = "id10"}, new poste {id = 15, poste_name = "id15"} }}); lcandidat.add(new candidat{ id = 1, num_cin = "abc15", postes = new collection<poste>() { new poste {id = 3, poste_name = "3"}, new poste {id = 4, poste_name = "id4"} }}); //get candidat var v = (from c in lcandidat c.num_cin == "abc15" && c.postes.any(p => p.id == 3) select c) .singleordefault(); var v2 = lcandidat.where(c => c.num_cin == "abc15" && c.postes.any(p => p.id == 3)) .select(c => c).singleordefault(); console.writeline("v query id {0}, cin {1}", v.id, v.num_cin); console.writeline("v2 query id {0}, cin {1}", v2.id, v2.num_cin);
result:
v query id 1, cin abc15 v2 query id 1, cin abc15
Comments
Post a Comment