【问题标题】:Combine Select Expression组合选择表达式
【发布时间】:2011-10-15 19:46:06
【问题描述】:

我想实现与Combine several similar SELECT-expressions into a single expression 非常相似的东西,但是代码不适用于我的情况。

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

作为一个例子看下面的代码:

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);
}

谁能帮帮我!

【问题讨论】:

  • however the code is not working for my case. 错误描述是什么意思?
  • 我更新了代码,以便您更好地理解并测试我的场景。 (我没有测试那个样本,但它应该可以工作)。谢谢

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


【解决方案1】:

你可以这样做:

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 不接受表达式,只接受委托。

【讨论】:

  • 感谢@leppie 提供的方法,但这不是我想要的。我想结合 keySelectors 来选择,因此它只会从数据库中选择这两个字段。
【解决方案2】:

我改变了实现,而不是组合选择表达式,我这样做了。它的情况略有不同,但我希望你能明白。

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});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多