DbSet.FirstOrDefault()?

Benjamin picture Benjamin · Nov 21, 2011 · Viewed 18.1k times · Source

I'm trying to do this but it says I can't use FirstOrDefault,

public static int GetId(this Context db, Type type, string name)
{
    return db.Set(type).FirstOrDefault(x => x.Name == name).Id;
}

The error is 'System.Data.Entity.DbSet' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Data.Entity.DbSet' could be found (are you missing a using directive or an assembly reference?)

I then tried this Cast method but that gave an error Cannot create a DbSet from a non-generic DbSet for objects of type 'WindowStyle' (btw WindowStyle inherits from DomainEntity below),

var set = db.Set(type).Cast<DomainEntity>();
return set.FirstOrDefault(x => x.Name == name).Id;

Here is the class,

public class DomainEntity
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

Answer

riseres picture riseres · Apr 28, 2013

Maybe you are missing

using System.Linq;