c# - 实体或复杂类型 'x' 无法在 linq to entities 查询中构建

标签 c# entity-framework ef-code-first linq-to-entities csla

谁能告诉我以下代码有什么问题,因为我在运行时在主题中遇到了这个错误:

我的具体 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 框架,但这在这件事上应该没有任何区别。

我看到论坛中有类似的问题,但没有一个能真正 100% 回答我的问题,因为我使用的是 DTO(我发现的所有问题从一开始就没有使用)。

任何帮助将不胜感激。

谢谢, 彼得

最佳答案

您可以让您的 CustomerDto 派生自 Customer...

public class CustomerDto : Customer { }

public List<CustomerDto> Fetch(int categoryID)
{
    return (from p in db.Products
            select new CustomerDto()
            {
                CustomerId = r.CustomerId,
                Name = r.Name,
                Email = r.Email
            }).ToList();
}

关于c# - 实体或复杂类型 'x' 无法在 linq to entities 查询中构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29897985/

相关文章:

c# - EF 中的多个 where 条件

c# - EF Code First INSERT 语句与 FOREIGN KEY 约束冲突

c# - Entity Framework ICollection 创建内表

c# - Visual Studio Code launchurl 不适用于 Web API

c# - 如何创建在 Visual Studio 中使用的新语言

c# - 使用 zxing 读取图像中的二维码

c# - 首先使用 EF 5 数据库进行延迟加载

c# - 在 C# 中对对象数组进行排序(相当于 std::sort)

.net - 我可以为此使用 Entity Framework 吗?

c# - Entity Framework 5,从代码优先切换到数据库优先?