我是Entity Framework的新手。
我有3张桌子。
候选人:Id,cin Poste:Id PosteCandidats:candidat_id,poste_id
我想得到一个候选人(cin ='abc15'和poste_id = 3)
我的模特:
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;}
}
生成关联表PosteCandidats。
我试过这个:
我尝试了这个,但它给了我一个错误
var v = _db.Candidats
.Where(c => c.num_cin == "abc15"
&& c.postes.Any(pc => pc.Id == 3));
var candi = v.SingleOrDefault();
但它没有给我什么
(我认为问题在于Any()方法)
答案 0 :(得分:0)
两个都有效的样本:
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
where 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);
结果:
v query ID 1, cin abc15
v2 query ID 1, cin abc15