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.