DbSet.FirstOrDefault ()?

I am trying to do this, but it says that I cannot 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 " System.Data.Entity.DbSet" does not contain a definition for "FirstOrDefault" and no extension method "FirstOrDefault" that takes the first argument of the type "System.Data.Entity.DbSet" may (you are missing the using directive or the assembly reference ?)

Then I tried this method Cast, but it gave an error. Failed to create a DbSet from a non-generic DbSet for objects of type WindowStyle (btw WindowStyleinherits from DomainEntitybelow).

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; }
}
+5
source share
6

, , , "" , , , . , :

public static class MyExtensions
{
    public static int? GetId<TEntity>(this Context db, string name)
        where TEntity : DomainEntity
    {
        return db.Set<TEntity>()
            .Where(x => x.Name == name)
            .Select(x => (int?)x.Id)
            .FirstOrDefault();
    }
}

, , . , , . nullable int , .

:

int? id = db.GetId<WindowStyle>("abc");

, WindowStyle .

, DomainEntity ( DbSet<DomainEntity>), . @Paul Keister .

Edit

:

public static class MyExtensions
{
    public static int? GetId(this Context db, Type entityType, string name)
    {
        return ((IQueryable<DomainEntity>)db.Set(entityType))
            .Where(x => x.Name == name)
            .Select(x => (int?)x.Id)
            .FirstOrDefault();
    }
}

:

int? id = db.GetId("abc", someType);

, , someType DomainEntity. . , .

+8

,

using System.Linq;
+23

, - DbSet, FirstOrDefault, . , , - DbSet. , Cast(), DbSet DbSet. , , DbSet ( , WindowsStyle). , Covariance DbSets, DbSets .

, , . LINQ . , , , ?

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

, , , , , , , . - DomainEntity.

+6

. DbSet Cast<T>(), (, Cast<WindowStyle>()), Cast<DomainEntity>() .

IQueryable.Cast<T>(), . :

var set = ((IQueryable)db.Set(type)).Cast<DomainEntity>();
return set.First(x => x.Name == name).Id;
+3

, , , .

public static int GetId(this Context db, Type type, string name)
{
    var set = db.Set(type);
    foreach (dynamic entry in set)
        if (entry.Name == name)
            return entry.Id; 
}
+2

set.Where(x => x.Name == name).Select(o=>o.Id).FirstOrDefault();

, .

0

All Articles