how can i write a generic query with EF and C#

c# entity-framework-6

Question

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));

    }
}
1
0
6/8/2016 9:28:52 AM

Accepted Answer

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.

0
6/8/2016 9:39:08 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow