【发布时间】:2015-07-06 00:55:31
【问题描述】:
谁能告诉我以下代码有什么问题,因为我在运行时在主题中收到此错误:
我的具体 DAL:
public class CustomerDal : ICustomerDal
{
public List<CustomerDto> Fetch()
{
using(var ctx = DbContextManager<CustomerContext>.GetManager("CustomerDB"))
{
var result = from r in ctx.DbContext.Customers
select new CustomerDto
{
CustomerId = r.CustomerId,
Name = r.Name,
Email = r.Email
}
return result.ToList();
}
}
我的数据上下文:
public class CustomerContext : DbContext
{
public CustomerContext(string connectionName)
: base(connectionName)
{
}
public DbSet<CustomerDto> Customers { get; set; }
}
我的 DTO:
public class CustomerDto
{
[Key]
public int CustomerId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
该数据库是一个名为 CustomerDB 的 LocalDb 数据库,以及一个名为 Customer 的表,其中包含 CustomerId、Name 和 Email 列。
我确实注意到,如果我使用匿名函数将 DAL 代码更改为以下代码,它可以正常运行,但我仍然没有从数据库中获取任何数据:
public List<CustomerDto> Fetch()
{
using(var ctx = DbContextManager<CustomerContext>.GetManager("CustomerDB"))
{
var result = (from r in ctx.DbContext.Customers
select new
{
CustomerId = r.CustomerId,
Name = r.Name,
Email = r.Email
}).ToList().Select(x => new CustomerDto{ CustomerId = x.CustomerId, Name = x.Name, Email = x.Email });
return result.ToList();
}
}
我也在使用 CSLA 框架,但这对这件事没有任何影响。
我看到论坛中有类似的问题,因为我使用的是 DTO(我发现的所有问题从一开始都没有使用),所以没有一个能真正 100% 回答我的问题。
任何帮助将不胜感激。
谢谢, 彼得
【问题讨论】:
-
问题主要是linqtoentities不支持整个linq功能。如果您想做与 dto 类似的事情,...您需要执行 ToList() 然后选择 dto。对于使用方法的复杂机制也是如此(即使是 linq 通常支持的一些内置方法也会导致相同的错误)
-
除了正常我会说你的“anynymous”代码应该会产生结果。如果 (from r in ctx.DbContext.Customers select r).ToList() 没有任何结果,您是否也尝试过调试?
-
不完全(可能是因为这个,我的措辞有点糟糕)。顺便说一句,我刚刚看到您在 dto 中使用 [Key]?如果仍然抛出错误,您是否已经尝试删除它? (据我阅读 EF 使用的关键注释,因此可能导致 EF 错误地解释 customerDto 是一个实体)
-
@Thomas,如果我删除 [Key]-attribute 我会在'return result.ToList()'之前收到以下错误:“在模型生成期间检测到一个或多个验证错误:CSLAEFCodeFirstTest .DalEf.CustomerDto: : EntityType 'CustomerDto' 没有定义键。为此 EntityType.Customers 定义键:EntityType: EntitySet 'Customers' 基于没有定义键的类型 'CustomerDto'
-
..我也意识到我在第一个例子中没有得到任何数据。它通过查询但在'return result.ToList()'处停止。我错过了什么?
标签: c# entity-framework ef-code-first linq-to-entities csla