EntityFramework Get object by ID?

前端 未结 8 762
旧巷少年郎
旧巷少年郎 2020-12-23 20:48

Is it possible with Generics to get an object from my EntityFramework without knowing the type?

I\'m thinking of something along the lines of:

public         


        
8条回答
  •  天命终不由人
    2020-12-23 21:33

    It's hard to make a completely generic solution because Entities can have composite keys, but this will work for a simple single key case.

    The key is to restrict T to be of type System.Data.Objects.DataClasses.EntityObject, which then has as EntityKey property (which represents the primary key).

    static T GetById(object id) where T : EntityObject
    {
        using (var context = new MyEntities())
        {
            return context.CreateObjectSet()
                .SingleOrDefault(t => t.EntityKey.EntityKeyValues[0].Value == id);
        }
    }
    

提交回复
热议问题