0

i want to write a query in entity framework like this:

T entity = (from e in myContext.typeof(T) )

i tried to use string concat but this dose not work for get a member from myContext

more code:

public T GetEntity<T>(Guid entityId, string connectionString)
{
    using (RContext rpContext = new RContext(connectionString))
    {

        var entity = (from e in rpContext.Set<T>()
                                    where e.Id == entityId
                                    select e).FirstOrDefault();
                    return (T) Convert.ChangeType(entity, typeof(T));

    }
}
data
  • 83
  • 2
  • 11

1 Answers1

1

You can access the generic Set method like this:

var entities = (from e in myContext.Set<T>());

Update: You will need to add generic type constraints to your method, to ensure the generic type T will match the constraints already applied to the method DbContext.Set<T>.

Update 2: You don't need to cast your entity; it is already typeof(T).

public T GetEntity<T>(Guid entityId, string connectionString)
    where T : class
{
    using (RContext rpContext = new RContext(connectionString))
    {

        return (from e in rpContext.Set<T>()
                where e.Id == entityId
                select e).FirstOrDefault();
    }
}

Update 3: You can pass your predicate straight into the FirstOrDefault method, assuming you're not attached to the linq syntax.

public T GetEntity<T>(Guid entityId, string connectionString)
    where T : class
{
    using (RContext rpContext = new RContext(connectionString))
    {
        return rpContext.Set<T>().FirstOrDefault(e => e.Id == entityId);
    }
}

Update 4: As you're using the Id property inside your method, you will also need to constrain your method to types which have that property - either by constraining a common interface, or a common base class. If it's a base class, you can remove the class constraint.

christophano
  • 915
  • 2
  • 20
  • 29