2

我正在尝试解决将 EF 实体映射到用作 DTO 的 POCO 的问题。

我的数据库中有两个表,比如产品和类别。一个产品属于一个类别,一个类别可能包含许多产品。我的 EF 实体被命名为 efProduct 和 efCategory。在每个实体中,efProduct 和 efCategory 之间都有适当的导航属性。

我的 Poco 对象很简单

public class Product
{
    public string Name { get; set; }
    public int ID { get; set; }
    public double Price { get; set; }
    public Category ProductType { get; set; }
}

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Product> products { get; set; }
}

要获取产品列表,我可以执行以下操作

    public IQueryable<Product> GetProducts()
    {
        return from p in ctx.Products
               select new Product
               {
                   ID = p.ID,
                   Name = p.Name,
                   Price = p.Price
                   ProductType = p.Category
               };
    }

但是存在类型不匹配错误,因为 p.Category 的类型为 efCategory。我该如何解决这个问题?也就是说,如何将 p.Category 转换为 Category 类型?

同样,当我这样做时

        return from c in ctx.Categories
                where c.ID == id
                select new Category
                {
                    ID = c.ID,
                    Name = c.Name,
                    ProductList = c.Products;
                };

我得到一个不匹配,因为 ProductList 是 Product 类型,其中 c.Products 是一个 EntityCollection

我知道 .NET EF 增加了对 POCO 的支持,但我不得不使用 .NET 3.5 SP1。

4

1 回答 1

4
    return from p in ctx.Products
           select new Product
           {
               ID = p.ID,
               Name = p.Name,
               Price = p.Price
               ProductType = new Category
               {
                   ID = p.Category.ID,
                   Name = p.Category.Name // etc.
               }
           };

Category你做:

    return from c in ctx.Categories
            where c.ID == id
            select new Category
            {
                ID = c.ID,
                Name = c.Name,
                ProductList = from p in c.Products
                              select new Product
                              {
                                  ID = p.ID,
                                  Name = p.Name,
                                  Price = p.Price
                              }
            };
于 2010-06-10T12:56:41.290 回答