'System.Data.Entity.Core.EntityCommandExecutionException' 发生在 EntityFramework.SqlServer.dll 但未在用户代码中处理

'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

我在下面做了 SQL 原始查询 select 只有来自 table.

的某些字段
{
 List<CustEmpVM> CustomerVMlist = new List<CustEmpVM>();
 var cid = db.Customers.SqlQuery("select SchedDate from Customer where CustID = '@id'").ToList<Customer>();
}

但我不断收到以下错误: System.Data.Entity.Core.EntityCommandExecutionException 发生在 EntityFramework.SqlServer.dll 但未在用户代码中处理

Additional information: The data reader is incompatible with the specified ALFHomeMovers.Customer. A member of the type, CustID, does not have a corresponding column in the data reader with the same name.

使用以下查询而不是原始查询:

{
 List<CustEmpVM> CustomerVMlist = new List<CustEmpVM>();
 var cid = db.Customers.Where(w=>w.Id == YOURCUSTOMERID).Select(s=>new Customer{SchedDate = s.SchedDate }).ToList();
}

它会给出编译时错误而不是运行时间错误。

异常消息非常简单:查询预期 return Customer table 的完整实体,但只有 SchedDate 列 returned,因此EF 无法完成映射其他省略的列,包括 CustID.

假设 CustomersDbSet<Customer>,尝试 return 来自 Customer 的所有字段:

// don't forget to include SqlParameter
var cid = db.Customers.SqlQuery("SELECT * FROM Customer WHERE CustID = @id", 
                                new SqlParameter("id", "[customer_id]")).ToList();

如果您只想 returning SchedDate 列,请具体化查询结果并在之后使用 Select

var cid = db.Customers.SqlQuery("SELECT * FROM Customer WHERE CustID = @id", 
                                new SqlParameter("id", "[customer_id]"))
                      .AsEnumerable().Select(x => x.SchedDate).ToList();

注意:我认为您可以根据上面的 SELECT 查询构造 LINQ:

var cid = (from c in db.Customers
           where c.CustID == "[customer_id]"
           select c.SchedDate).ToList();

类似问题:

The data reader is incompatible with the specified Entity Framework