Question

In an effort to further abstract my repository layer I have attempted to follow the code-first approach as described here: http://msdn.microsoft.com/en-us/magazine/ee236639.aspx.

I have a many-to-many relationship between Account and Subscription entities. A Navigation property exists on each entity pointing to the other (e.g. Account.Subscriptions).

Before I created my own model I was using the Entity generated model and the below worked fine ("db" is the entity context) :

public IQueryable<Account> GetBySubscriptionId(int subId)
{
    return from a in db.Accounts
           where a.Subscriptions.Any(s => s.SubscriptionId == subId)
           select a;
}

Now the model for Account looks like this:

public class Account
    {
        public int AccountId { get; set; }
        public string Name { get; set; }

        // nav properties
        public virtual List<Subscription> Subscriptions { get; set; }
}

And when I try to run the same LINQ query now I get this error:

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

Any suggestions greatly appreciated.

Was it helpful?

Solution

Try changing the signature from

        // nav properties 
        public virtual List<Subscription> Subscriptions { get; set; }

to

        // nav properties 
        public virtual ICollection<Subscription> Subscriptions { get; set; }

Shamelessly nicked from Scott Hanselmann's demo here - http://www.hanselman.com/blog/SimpleCodeFirstWithEntityFramework4MagicUnicornFeatureCTP4.aspx which uses this pattern, also here's a Scott Guthrie demo using the same idea http://weblogs.asp.net/scottgu/archive/2010/07/23/entity-framework-4-code-first-custom-database-schema-mapping.aspx .

List<T> is a concrete implementation of various interfaces (ICollection, IQueryable, IEnumerable etc), Entity Framework uses proxy objects when it retrieves things from the database, hence the virtual declarations, which use different implementations of these interfaces which is where your error is coming from.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top