c# - Entity frame work: many to many relationship tables -
i have news entity , news based on newsid. defined new entity , group , want news based on group id. defined group news table aslo relate table together. 
in news model have :
public virtual icollection<groupnews> relatedgroupid { get; set; } so assumed defined groupnews table values , can use in newsservice.
now lets @ newsservice :
expression<func<news, bool>> constraint = null; if (user_id > 0 && project_id > 0) { constraint = e => (e.creatorid == user_id && e.relatedprojecttags.any(p => p.projectid == project_id)); } else if (user_id > 0) { constraint = e => (e.creatorid == user_id); } else if (project_id > 0) { constraint = e => (e.relatedprojecttags.any(p => p.projectid == project_id)); } else { constraint = null; } ienumerable<news> result_list = null; if (constraint != null) { result_list = newsrepository.getmany(constraint).orderbydescending(e => e.createdon).skip(offset); } else { result_list = newsrepository.getall().orderbydescending(e => e.createdon).skip(offset); } if (count > 0) { result_list = result_list.take(count); } return result_list.tolist<news>(); } }
i add line in order define constraint based on groupid.
else if (groupid > 0) { constraint = e => (e.relatedgroupid.any(n => n.groupid == groupid)); } it seems wrong , gives me error :
{"invalid object name 'dbo.groupnewsnews'."}
1.you not need groupnewsid in groupnews table. need drop column , create complex key groupid , newsid. in news entity need define property:
public virtual icollection<group> groups { get; set; } in default constructor entity need initialize property(need lazy load):
groups = new list<group>(); similar changes group entity.
2.in groupmap.cs need define
this.hasmany(t => t.news) .withmany(t => t.groups) .map(m => { m.totable("groupnews"); m.mapleftkey("groupid"); m.maprightkey("newsid"); }); 3.write tests newsrepository , grouprepository.
Comments
Post a Comment