作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试解决将 EF 实体映射到用作 DTO 的 POCO 的问题。
我的数据库中有两个表,例如 Products 和 Categories。一个产品属于一个类别,一个类别可能包含许多产品。我的 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。
最佳答案
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
}
};
关于c# - EFv1 映射 1 到多 与 POCO 的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3009675/
我是一名优秀的程序员,十分优秀!