4

I have the following class:

public class BicycleSellerListing : IUserName
{
    public UserProfile UserProfile { get; set; }

    /// <summary>
    /// IUserName interface property
    /// </summary>
    public string UserName
    {
        get
        {
            return UserProfile.UserName;
        }
    }
}

The interface:

public interface IUserName
{
    string UserName { get; }
}

And this query:

public static List<T> GetList<T>(string userName) where T : class, IUserName
{
    using (SqlUnitOfWork work = new SqlUnitOfWork())
    {
        return work.GetList<T>(row => row.UserName == userName)
            .ToList();
    }
}

When I execute this query, I get the following exception:

The specified type member 'UserName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

I understand why I'm getting the exception, but am wondering if there is a way I can perform this query using the interface?

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
Randy Minder
  • 47,200
  • 49
  • 204
  • 358

3 Answers3

2

To answer you quistion:

Is it possible to query on an interface property?

Yes. it's no problem. The fault you are getting is not becuase of the interface.

The problem is that you can't query on properties that isn't mappe with Linq 2 Entities

Other people have had this propblem as well.

The underlying expressionbuilder can not distinct between properties that is mapped to the database, and properties that is not.

It is a problem becuase the compiler can't help you. In Linq to object, it is no problem, so the compiler doesnt throw any errors/warnings

You should try to make it clear the this property is not mapped - perhaps by a prefix, or a nested class that contains all the "custom" properties.

Community
  • 1
  • 1
Jens Kloster
  • 11,099
  • 5
  • 40
  • 54
0

In addition to the existing answer(s), you can perform the where in memory, but that means retrieving the whole table.

Normally I wouldn't recommend this though.

public static List<T> GetList<T>(string userName) where T : class, IUserName
{
    using (SqlUnitOfWork work = new SqlUnitOfWork())
    {
        return work.GetList<T>()
            .AsEnumerable()
            .Where(row => row.UserName == userName)
            .ToList();
    }
}
Maarten
  • 22,527
  • 3
  • 47
  • 68
0

Some workarounds:

  • You could try to determine underlying entity type in runtime and
    then dynamically compile and invoke a generic method executing query with this type.

  • It is possible to assemble this query manually in runtime using Expression class

  • You could try Entity SQL query syntax instead of Linq

Oleg Mikhailov
  • 252
  • 1
  • 8