如何组合Entitydatasource控件中两个表的记录?我用Google搜索并搜索了没有运气的SO。我需要的SQL是
SELECT DISTINCT username FROM
(SELECT s.username FROM project_stakeholders s
UNION
SELECT t.username FROM project_team_members t)
我的实体结构如下:
project_stakeholders
----------------------
project_stakeholders.record_id (PK)
project_stakeholders.username
project_stakeholders.project
project_stakeholders.project_id (FK)
project_stakeholders.status
project_team_members
---------------------
project_team_members.record_id (PK)
project_team_members.username
project_team_members.project
project_team_members.project_id (FK)
project_team_members.status
我发现这个问题几乎可以解答我的问题,但我的问题更为先进,因为我的SubQueries来自与主要实体无关的实体。
我已将我的数据源更改为LiqDatasource控件,并在LinqDatasource控件的Onselecting事件的代码后面添加了以下代码:
protected void TaskProfileDS_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
int project_id = 0;
if (Int32.TryParse(Request.QueryString["id"], out project_id))
{
using (MyEntitiesContext db = new MyEntitiesContext())
{
var TeamMembers = from tm in db.team_members where tm.project_id == project_id select tm.username;
var Stakeholders = from sh in db.project_stakeholders where sh.project_id == project_id select sh.username;
var result = from usr in db.project_profiles where (TeamMembers.Contains(usr.caption) || Stakeholders.Contains(usr.caption)) select usr;
e.Result = result;
}
}
}
但不幸的是,我收到以下错误:
由于已经处理了DbContext,因此无法完成操作。
任何想法都将受到高度赞赏。
答案 0 :(得分:1)
这是我从不相关的表(实体)中获取记录的代码。我使用了LinqDataSource,然后在QueryCreated事件中,我将查询更改为我自己的LINQ查询:
protected void TaskDS_QueryCreated(object sender, QueryCreatedEventArgs e)
{
int project_id = 0;
if (Int32.TryParse(Request.QueryString["id"], out project_id))
{
using (SDManagerEntities db = new SDManagerEntities())
{
List<project_profiles> usrs = new List<project_profiles>();
var users1 = db.team_members.Where(t => t.project_id == project_id).Select(it => it.username);
var users2 = db.project_stakeholders.Where(s => s.project_id == project_id).Select(it => it.username);
var allMembers = users1.Concat(users2);
foreach (var member in allMembers.Distinct())
{
project_profiles usr = db.project_profiles.SingleOrDefault(it => it.caption == member);
if (!usrs.Contains(usr))
{
usrs.Add(usr);
}
}
e.Query = usrs.AsQueryable().OrderBy(it => it.fullName);
}
}
}
我希望它可以帮助别人