在一对多关系中,两个类之间的Linq表达式
本文关键字:两个 之间 表达式 Linq 关系 一对多 | 更新日期: 2023-09-27 18:17:10
我有两个class:
public class Op
{
[Key]
public int OpId { get; set; }
private OpportunitiesDb db = new OpportunitiesDb();
[Required(ErrorMessage = "Opportunity title is required")]
[DisplayName("Opportunity Title")]
public string Title { get; set; }
[DisplayName("Tags")]
public ICollection<Tags> Tags { get; set; }
}
public class Tags
{
[Key]
public int Id { get; set; }
public int OpId { get; set; }
public string Tag { get; set; }
}
我有一个类的类型OpId。一个Op类可以有多个tag(一对多关系)。
这个OpId有一个标签让我们假设"Water"
现在我需要在标签中找到所有有"水"作为标签的操作。db上下文有2个表(Ops和Tags)。
控制器的动作是:public async Task QueryTags(int?id){If (id == null){return RedirectToAction("IdNotPresent", "Error");}
Op SelectedOp = db.Opportunities.Find(id);
//get tags for ID.
var Tags = db.Tags
.Where(s => s.OpId == id);
var model =
from r in db.Tags
where (r.OpId == id)
select r;
return PartialView(await model.ToListAsync());
}
Group by Tag
from r in db.Tags
join o in db.Ops on r.OpId equals o.OpId
group o by r.Tag into ops
select ops
按标签筛选以获得您正在查找的操作
我需要的是这个搜索,这将带来所有具有相同标签的操作字符串查询var:
var AllOpsWithTagQuery = from r in db.Tags
where(r.Tag.StartsWith(Query))
join o in db.Opportunities on r.OpId equals o.OpId
select o;