【问题标题】:generic GetById for complex PK用于复杂 PK 的通用 GetById
【发布时间】:2011-04-26 18:39:39
【问题描述】:

我正在寻找一种创建通用 GetById 的方法,该 GetById 将 params object[] 作为参数,知道找到 key/s 字段并知道找到相关实体。

在寻找解决方案的过程中,我想到了一个返回 PK 字段定义的通用方法和一个可以基于字段返回实体的通用方法。

我正在寻找可以在一个或多个字段作为主键的表中使用的东西。

编辑 一个或多个字段作为主键示例 =
表客户有(CompanyId、CustomerName、Address、CreateDate)。
客户的主键是 CompanyId 是 CustomerName。

我正在寻找通用的 GetById,它也知道处理这些表格。

【问题讨论】:

  • 你能举一个你想做的例子吗?你怎么能有“一个或多个字段作为主键”?你是说复合键吗?
  • 从概念上讲,这是否类似于编译器在选择正确的重载时需要做的事情?

标签: c# .net entity-framework


【解决方案1】:

如果您不知道密钥中有多少成员以及它们有哪些类型,则无法获得“通用”方法。我将my solution for single key 修改为多个键,但您可以看到它不是通用的 - 它使用定义键的顺序:

// Base repository class for entity with any complex key
public abstract class RepositoryBase<TEntity> where TEntity : class
{
    private readonly string _entitySetName;
    private readonly string[] _keyNames;

    protected ObjectContext Context { get; private set; }
    protected ObjectSet<TEntity> ObjectSet { get; private set; }

    protected RepositoryBase(ObjectContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        Context = context;
        ObjectSet = context.CreateObjectSet<TEntity>();

        // Get entity set for current entity type
        var entitySet = ObjectSet.EntitySet;
        // Build full name of entity set for current entity type
        _entitySetName = context.DefaultContainerName + "." + entitySet.Name;
        // Get name of the entity's key properties
        _keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
    }

    public virtual TEntity GetByKey(params object[] keys)
    {
        if (keys.Length != _keyNames.Length)
        {
            throw new ArgumentException("Invalid number of key members");
        }

        // Merge key names and values by its order in array
        var keyPairs = _keyNames.Zip(keys, (keyName, keyValue) => 
            new KeyValuePair<string, object>(keyName, keyValue));

        // Build entity key
        var entityKey = new EntityKey(_entitySetName, keyPairs);
        // Query first current state manager and if entity is not found query database!!!
        return (TEntity)Context.GetObjectByKey(entityKey);
    }

    // Rest of repository implementation
}

【讨论】:

  • @Ladislav Mrnka:您为什么将存储库标记为抽象?
  • @Ladislav Mrnka:这里的解决方案和这里的解决方案有什么区别:stackoverflow.com/questions/5166297/…
  • @Naor:EF 版本不同。这个是针对 ObjectContext API 和 EFv4 的,链接的是针对 DbContext API 和 EFv4.1
  • @Naor:我为什么要标记存储库摘要?因为我不相信通用存储库。通用存储库的想法只适用于非常简单的场景。
  • @Ladislav Mrnka:我在哪里可以找到有关 ObjectContext 与 DbContext 的文档?直到现在我还没有意识到有两种方法。这是否意味着 ObjectContext 将被 DbContext 取代?
【解决方案2】:

我不知道这会有多大用处,因为它是通用的,但你可以这样做:

public TEntity GetById<TEntity>(params Expression<Func<TEntity, bool>>[] keys) where TEntity : class
{
    if (keys == null)
      return default(TEntity);

    var table = context.CreateObjectSet<TEntity>();
    IQueryable<TEntity> query = null;
    foreach (var item in keys)
    {
        if (query == null)
            query = table.Where(item);
        else
            query = query.Where(item);
    }
    return query.FirstOrDefault();
}

然后你可以这样称呼它:

var result = this.GetById<MyEntity>(a => a.EntityProperty1 == 2, a => a.EntityProperty2 == DateTime.Now);

免责声明:这真的不是 GetByid,它真的是“让我给你几个参数并给我第一个匹配的实体”。但话虽如此,它使用泛型,如果存在匹配项并且您根据主键进行搜索,它将返回一个实体。

【讨论】:

  • 这和where一样。
  • @Naor,不完全是,返回 IQueryable&lt;TEntity&gt; 这将返回 TEntity
  • 所以这和 Single.. 是一样的 :)
【解决方案3】:

我认为您无法实现这样的事情,因为您将无法将每个传递的值与适当的键字段连接起来。

我建议为每个实体使用自定义方法:

假设CodeNamePerson 表中的键:

 public IEnumerable<Person> ReadById(int code, string name)
 {
     using (var entities = new Entities())
        return entities.Persons.Where(p => p.Code = code && p.Name = name);
 }

【讨论】:

  • 但这正是我想要避免的——编写每个类的 GetById 方法。
  • @Napr:在我看来没有通用的方法,但我认为它们不会太多。
【解决方案4】:

好的,这是我的第二次尝试。我认为这对你有用。

public static class QueryExtensions
{
    public static Customer GetByKey(this IQueryable<Customer> query, int customerId,string customerName)
    {
        return query.FirstOrDefault(a => a.CustomerId == customerId && a.CustomerName == customerName);
    }

}

所以这个扩展方法背后的美妙之处在于你现在可以这样做:

Customer customer = Db.Customers.GetByKey(1,"myname");

你显然必须为每种类型都这样做,但如果你需要它可能值得:)

【讨论】:

  • 何塞,这是一个很好的答案,但我正在寻找一种通用的方法来支持多个字段作为主键。在您的版本中,我必须为每个类编写一个方法,并使该方法具有通用性,这会使具有多个字段为 pk 的表出现问题。
【解决方案5】:

我认为设置有点,但我确实认为创建一个可重用的模式从长远来看会有所回报。我只是写了这个,还没有测试,但我基于我经常使用的搜索模式。

所需接口:

public interface IKeyContainer<T>
{
    Expression<Func<T, bool>> GetKey();
}

public interface IGetService<T>
{
    T GetByKey(IKeyContainer<T> key);
}

示例实体:

public class Foo
{
    public int Id { get; set; }
}

public class ComplexFoo
{
    public int Key1 { get; set; }

    public int Key2 { get; set; }
}

实现示例:

public class FooKeyContainer : IKeyContainer<Foo>
{
    private readonly int _id;

    public FooKeyContainer(int id)
    {
        _id = id;
    }

    public Expression<Func<Foo, bool>> GetKey()
    {
        Expression<Func<Foo, bool>> key = x => x.Id == _id;
        return key;
    }
}

public class ComplexFooKeyContainer : IKeyContainer<ComplexFoo>
{
    private readonly int _id;
    private readonly int _id2;

    public ComplexFooKeyContainer(int id, int id2)
    {
        _id = id;
        _id2 = id2;
    }

    public Expression<Func<ComplexFoo, bool>> GetKey()
    {
        Expression<Func<ComplexFoo, bool>> key = x => x.Key1 == _id && x.Key2 == _id2;
        return key;
    }
}

public class ComplexFooService : IGetService<ComplexFoo>
{
    public ComplexFoo GetByKey(IKeyContainer<ComplexFoo> key)
    {
       var entities = new List<ComplexFoo>();            
       return entities.Where(key.GetKey()).FirstOrDefault();
    }
}

用法:

var complexFoo = ComplexFooService.GetByKey(new ComplexFooKeyContainer(1, 2));

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 2013-12-19
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多