Linq to sql:将子行合并为一个单独的实体

时间:2011-11-27 15:23:37

标签: linq-to-sql

我有三张桌子:

预置:

ID int PK,
Name nvarchar

Preset_milestone_presets :(链接表)

presetId int PK, FK to Preset-table.
milestoneId int PK

Preset_titles_presets :(链接表)

presetId int PK, FK to Preset-table.
titleId int PK

和C#实体一样:

预设:

int[] milestoneIds
int[] titleIds

所以我想知道使用linq-to-sql的最佳方法是在单个实体上创建,该实体具有代表多个预设的milestoneIdstitleIds的合并不同列表。 (加入Presets表中的多行?)

编辑: 数据示例:

普列斯特斯

1   "Preset 1"
2   "Preset 2"

Preset_milestone_presets

1   1
1   2
1   3
1   4
2   1
2   5
2   6

Preset_titles_presets

1   1
1   2
2   1
2   3
2   4

请求具有id 1和2的预设时的预期结果是具有以下数组的单个实体:     milestoneIds:{1,2,3,4,5,6}     titleIds:{1,2,3,4}

1 个答案:

答案 0 :(得分:1)

我希望此代码对您有所帮助:

Dictionary<string, List<int>> result = 
   new Dictionary<string, List<int>>();

/*id's */
List<int> ids = new List<int>(new int[] { 1,2 });

/* Tanking Prestes */
var my_presets = 
   (from p in Prestes 
    join i in ids
    on p.id = i
    select p);

/*Taking Milestones*/
my_milestones_ids = 
   (from m in Preset_milestone_presets 
    join p in my_presets
    on m.idPreset = p.id
    select m.id).Distinct().ToList();

/*Taking titles*/
my_titles_ids = 
   (from t in Preset_titles_presets 
    join p in my_presets
    on t.idPreset = p.id
    select t.id).Distinct().ToList();

/* result */
result.Add( "presets_ids", ids);
result.Add( "milestones_ids", my_milestones_ids);
result.Add( "titles_ids", my_titles_ids);

如果您不喜欢加入,请尝试:

/* Tanking Prestes */
var my_presets = 
   (from p in Prestes 
    where ids.Contains( p.id)
    select p);

/*Taking Milestones*/
my_milestones_ids = 
   (from m in Preset_milestone_presets 
    where my_presets.Contains( m.Preset) 
    select m.id).Distinct().ToList();

/*Taking titles*/
my_titles_ids = 
   (from t in Preset_titles_presets 
    where my_presets.Contains( t.Preset) 
    select t.id).Distinct().ToList();