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; }
}
This answer possibly doesn’t help you depending on how “dynamic” the situation is where you call this method, basically if you know the type at compile time or not. If you know it you can write a generic method instead:
I’ve changed it to a projection because you don’t need to load the full entity if you only want the Id. You can let the database do the work to select the property to improve performance a bit. Also I return a nullable int in case that there is no match for the name in the database.
You can call this in your code like so:
As you can see for this solution you must specify the type
WindowStyleat compile time.This assumes that
DomainEntityis not part of your model (there is noDbSet<DomainEntity>), but just a base class of your entities. Otherwise @Paul Keister’s solution would be easier.Edit
Alternatively you can also try the following:
And call it:
It will throw an exception though at runtime if
someTypedoes not inherit fromDomainEntity. The generic version will check this at compile time. So, if you can prefer the first version.