Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

c# - DbSet doesn't contain definition for FirstOrDefault?

I recently migrated an existing project to .net 4.5 and changed out what this project was using for data access (switching to Entity Framework).

For some reason any time I try to access any functions for a DbSet (Where, First, FirstOrDefault, etc) it throws the error:

Error 53 'System.Data.Entity.DbSet1<MyProject.Data.Customer>' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Data.Entity.DbSet1' could be found (are you missing a using directive or an assembly reference?

This uses .net 4.5 and I read that these functions are no longer in System.Linq but are now stored in System.Core. I have added a reference to System.Core to the project but I am still getting the error. There is a using statement for System.Linq, but not for System.Core.

Can anyone see why I would be getting this error? Suggestions on how to fix?

UPDATE:

This is the line that throws the error:

VIModel Db = new VIModel();
Customer = Db.Customers.FirstOrDefault(c => c.CustomerId == CustomerId && c.IsPrimary);

and my DbContext:

public partial class VIModel : DbContext
{
     ........
     public virtual DbSet<Customer> Customers { get; set; }
     ........
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The assembly for Queryable (the thing that adds the FirstOrDefault extension method you are using) is in System.Core, however it's namespace is System.Linq, you can see this on the MSDN page for it

Namespace: System.Linq
Assembly: System.Core (in System.Core.dll)

You need to have in your project a refrence to System.Core and in the file you are trying to use it a using System.Linq;

If you have both of these things double check that your project or some project you are refrencing did not create it's own System.Data.Entity.DbSet<T> class which does not implement IQueryable<T> or IEnumerable<T>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...