Is it possible to request an interface property?

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; } } } 

Interface:

 public interface IUserName { string UserName { get; } } 

And this request:

 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 request, I get the following exception:

The specified member of type 'UserName' is not supported in LINQ to Entities. Only initializers, entities, and property entities are supported.

I understand why I am getting an exception, but I am wondering if there is a way to execute this request using the interface?

+4
source share
3 answers

To answer quistion:

 Is it possible to query on an interface property? 

Yes. It's not a problem. The error you are getting is not related to the interface.

The problem is that you cannot request properties that are not mappe with Linq 2 Entities

Other people also had this sign.

The builder to be expressed cannot distinguish between properties that map to the database and properties that are not.

This is a problem because the compiler cannot help you. In Linq, this is not a problem for the object, so the compiler does not throw any errors / warnings

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

+2
source

In addition to the existing answers, you can do what is in memory, but that means getting the whole table.

Normally, I would not recommend this.

 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(); } } 
0
source

Some workarounds:

  • You can try to determine the type of the base object at runtime and
    then dynamically compile and call the generic method that executes the request with this type.

  • This query can be assembled manually at run time using the Expression Class

  • You can try Entity SQL query syntax instead of Linq

0
source

Source: https://habr.com/ru/post/1469492/


All Articles