I'm in the early stages of learning to use Entity Framework 4.1 using the book "Programming Entity Framework" using C# in VS2010. I've run into a problem that's probably obvious to an experienced EF programmer.
“System.Linq.IQueryable' does not contain a definition for 'Title' and no extension method 'Title' accepting a first argument of type 'System.Linq.IQueryable' could be found (are you missing a using directive or an assembly reference?)
The ‘contacts’ fields are identified correctly in the pop-up help, but trying to access those fields generates the error shown above. While typing in ‘contacts’, the pop-up fields list does not contain any of the underlined fields.
I don’t und开发者_如何转开发erstand this inconsistency and would welcome your help.
var contacts = (from c in context.Person_Contacts
where c.FirstName == "Robert"
select new { c.Title, c.FirstName, c.LastName }).FirstOrDefault();
Console.WriteLine("{0} | {1} | {2}", contacts.Title, contacts.FirstName, contacts.LastName);
Console.ReadLine();
Try that
contacts
is of type IQueryable
which itself implements IEnumerable
, so whtat you are actually looking at, is a collection of contacts, not a single one. But you trying to access a specific contact within the list.
You can either wrap you Console.WriteLine
method in a foreach loop to print out all contacts, like so:
foreach (var contact in contacts.ToList()) // ToList will cause EF to perform the SQL query and load the complete results in a list.
{
Console.WriteLine("{0} | {1} | {2}", contact.Title, contact.FirstName, contact.LastName);
}
If you are only looking for a single contact, you can use either the First(), Last() or Single() method, which will return the corresponding entity.
var contact = contacts.FirstOrDefault(); // Get the first contact with the specified name or a null-reference if the query has no results:
if (null != contact)
{
Console.WriteLine(...)
}
精彩评论