user979331 user979331 - 2 months ago 17
C# Question

ASP.NET Entity framework Cannot implicitly convert type

I got a line of code like so:

ProjectClass pricing = db.Data.Where(model => model.collection == “aaa”);


but I get this error:

Cannot implicitly convert type 'System.Linq.IQueryable<ProjectName.Models.ProjectClass>' to 'ProjectName.Models.ProjectClass'. An explicit conversion exists (are you missing a cast?)


What Am I doing wrong?

Here is my ProjectClass

public class ProjectClass
{
[Key]
public int id { get; set; }
[DisplayName("Design")]
public string name { get; set; }
[DisplayName("Price")]
[DisplayFormat(DataFormatString = "{0:n0}")]
public int basePrice { get; set; }
[DisplayName("Size")]
public int sqft { get; set; }
[DisplayName("Collection")]
public string collection { get; set; }
[DisplayName("Hidden")]
public bool hidden { get; set; }
}

Answer

Querys for results with any quantity of results use Where

 List<ProjectClass> result = db.Data.Where(model => model.collection == “aaa”).ToList(); 

Querys for only 0 or 1 result use SingleOrDefault

 var result = db.data.SingleOrDefault(model => model.collection == "aaa");

The result will be null if no record matched.

For querying the first matching record use FirstOrDefault

var result = db.data.FirstOrDefault(model => model.collection == "aaa");

The result will be null if no record matched.