简体   繁体   中英

the entity or complex type 'x' cannot be constructed in a linq to entities query

Can anyone tell me what is wrong with the following code since I get this error in the subject when run:

My concrete 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();
        }
    }

My data context:

public class CustomerContext : DbContext
{
    public CustomerContext(string connectionName)
        : base(connectionName)
    {
    }

    public DbSet<CustomerDto> Customers { get; set; }
}

My DTO:

public class CustomerDto
{
    [Key]
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

The database is a LocalDb-database with the name CustomerDB, and a table called Customer with the columns CustomerId, Name, and Email.

I did notice though that if I change the DAL-code to the following, using an Anonymous function, it runs without error, but I still don't get any data from the database:

    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();
        }
    }

I'm also using the CSLA framework but that shouldn't make any difference in this matter.

I have seen that there is similar questions in the forum, bun none that really answers my question to 100% since I'm using a DTO (which all questions I found didn't make use of from the beginning).

Any help would be very appreciated.

Thanks, Peter

You could have your CustomerDto deriving from 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM