0

Our database has a Primary Key defined on every table existing of a combined key with a short and an int. Therefore, using Entity Framework we can try to find an element by calling to it's Context.DbSet<>.Find(params object[] parameters) method. In our code this would look like:

public Client FindClient(short sqlId, int incId)
{
  Context db = new Context();
  Client result = db.Clients.Find(sqlId, incId);
  return result;
}

However, in our code we are using structs to store key values. Our struct is as follows:

public struct DbKey
{
  private short _SqlId;
  private int _IncId;
  public short SqlId { get { return _SqlId; } }
  public int IncId { get { return _IncId; } }

  public DbKey(short SqlId, int IncId)
  {
    this._SqlId = SqlId;
    this._IncId = IncId;
  }

and has some other comparing methods etc. We would like to be able to call the DbSet.Find method like this:

public Client FindClient(DbKey key)
{
  Context db = new Context();
  Client result = db.Clients.Find(key);
  return result;
}

To be able to do this we wrote an extension overload for this method:

public static partial class Extensions
{
  public static T Find<T>(this DbSet<T> dbset, DbKey key) where T : class
  {
    return dbset.Find(key.IncId, key.SqlId);
  }
}

Intellisense now tells us the Find method is overloaded, with one version accepting DbKey key as parameter, and the other, original method accepting params object[] parameters. However, when running the code, the function will always call to the original method and never to the overloaded, since DbKey also matches the original parameters, resulting in an exception. How can we solve this problem?

  • [Closer is better](http://ericlippert.com/2013/12/23/closer-is-better/) Rename your extension method. That's the only thing I can think of. Or call it as `Extensions.Find` instead – Sriram Sakthivel Nov 13 '14 at 07:59
  • it is because it takes your object in to its object[] why not change your extension name like FindCustom – Ehsan Sajjad Nov 13 '14 at 07:59

1 Answers1

1

Well, you can rename, or call static extension directly:

public Client FindClient(DbKey key)
{
  Context db = new Context();
  Client result = Extensions.Find(db.Clients, key);
  return result;
}
Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78
  • To elaborate: the extension method rules specifically disregard the extension method if there is a non-extension method that matches the call site, even if overload ordinarily would prefer the extension method. The extension method is not _really_ an overload, because it's not actually in the same type. Calling it explicitly resolves the ambiguity by forcing the non-overloaded method from the extension-method's class to be used. – Peter Duniho Nov 13 '14 at 08:28