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

风流意气都作罢 提交于 2019-12-12 03:46:58

问题


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:


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.



来源:https://stackoverflow.com/questions/37697161/how-can-i-write-a-generic-query-with-ef-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!