0

Assuming that AccountSet returns an IQueryable<Account>, how can I convert this early binding:

XrmServiceContext _xrmServiceContext;
var result = _xrmServiceContext.AccountSet.FirstOrDefault(x => x.Id == locationGuid);

Into something that is more reusable like:

_xrmServiceContext.Where(Set == "Account").FirstOrDefault(x => x.Id == locationGuid);

AccountSet is defined as:

    public System.Linq.IQueryable<Xrm.Account> AccountSet
    {
        get
        {
            return this.CreateQuery<Xrm.Account>();
        }
    }

How do I generalize this to be reusable for any IQueryable member of XrmServiceContext ?

Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • this is similar to what i would like to do but it uses reflection, something that i want to avoid, http://stackoverflow.com/a/38198824/6761907 – Alex Gordon Feb 24 '17 at 21:20

2 Answers2

1

As long as the Id is the primary key you can use that in conjunction with find to make a generic call

public T Get<T>(object[] Id)
      where T : class
{
    return _xrmServiceContext.Set<T>().Find(Id )
}

if your looking for an IQueryable that may be a bit harder but you can find out how to do that off of a previous question I asked:

Entity Framework Filter By PrimaryKey

Community
  • 1
  • 1
johnny 5
  • 19,893
  • 50
  • 121
  • 195
1

Courtesy of this post, I've found the following solution:

private static T EntityGet<T>(Guid id)
    where T : Entity
{
    T item =
    (
        from query in Context.CreateQuery<T>()
        where query.Id == id
        select query
    ).Single();

    return item;
}
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062