结合选择表达式

时间:2011-10-15 19:46:07

标签: c# lambda entity-framework-4.1 expression expression-trees

我想实现与此Combine several similar SELECT-expressions into a single expression非常相似的内容,但代码对我的情况不起作用。

我想传递2个keySelectors(属性),并希望将它们组合起来用于EF 4.1 select查询。

仅作为示例,请参阅以下代码:

public class Category
{
    public int CategoryId { get; set; }
    [Required(ErrorMessage = "Name required.")]
    [StringLength(25, ErrorMessage = "Must be less than 25 characters.")]
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime? CreateDateTime { get; set; }
}

public class SampleContext : DbContext
{
    public SampleContext() : base("Sketch7.Sample") { }

    public DbSet<Category> Categories { get; set; }
}

public static class Repository
{

    public Dictionary<TKey, TKeyValue> GetKeyValue<TKey, TKeyValue>(Expression<Func<TEntity, TKey>> keySelector, Expression<Func<TEntity, TKeyValue>> valueKeySelector)
    {
        var combined = //ToDo Select Combine here...

        SampleContext db = new SampleContext(); 
        var result = db.Categories.Select(combined);
        ...
        return dictionary;
    }
}

使用

public void GetKeyValueTest()
{
    Repository.GetKeyValue(x => x.Id , x => x.Name);
}

任何人都可以帮助我!

2 个答案:

答案 0 :(得分:0)

你可以这样做:

public Dictionary<TKey, TKeyValue> GetKeyValue<TKey, TKeyValue>
    (Func<Category, TKey> keySelector, 
     Func<Category, TKeyValue> valueKeySelector)
{
    var combined = //ToDo Select Combine here...

    SampleContext db = new SampleContext(); 
    var result = db.Categories.Select(combined);
    ...
    return result.ToDictionary(keySelector, valueSelector);
}

注意:

  1. TEntity必须通过或具体
  2. ToDictionary不接受表达式,只接受委托。

答案 1 :(得分:0)

我更改了实现,而不是组合选择表达式,我这样做了。它的情况略有不同,但我希望你能得到这个想法。

public class KeyValue<TKey, TValue>
{
    public TKey Key { get; set; }
    public TValue Value { get; set; }
}

public Dictionary<TKey, TValue> GetKeyValue<TKey, TValue>(Expression<Func<TEntity, KeyValue<TKey, TValue>>> keySelector)
{
    return _dbset.Select(keySelector).ToDictionary(x => x.Key, x => x.Value);
}

public Dictionary<int, string>  GetIndustriesKeyValue()
{
    return IndustryRepository.GetKeyValue(x => new KeyValue<int, string> {Key = x.Id, Value = x.Name});
}
相关问题