[英]Can an Entity Framework Context return a class that inherits a Entity
I have an Entity Framework 5 Code First DbContext 我有一个Entity Framework 5 Code First DbContext
public class ProductContext : DbContext
{
public DbSet<Product> Products {get;set;}
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
}
Now I have to implement an interface but don't want to pollute my model so I create a 现在,我必须实现一个接口,但是不想污染我的模型,所以我创建了一个
public class ProductEx : Product, ISomeInterface
{
public bool ISomeInterface.SomeMethod() { return false; }
}
I know I could do: 我知道我可以做:
var query = from p in context.Products
select new ProductEx { p.ProductId, p.Name };
But since the DbContext already returns a dynamic proxy (because of change tracking / lazy loading) maybe there is a better approach. 但是由于DbContext已经返回了动态代理(由于更改跟踪/延迟加载),所以也许有更好的方法。 I am thinking about something like this:
我在想这样的事情:
var query = from p in context.Products.As<ProductEx>()
select p;
the entities should be a dynamic proxy inherited from ProductEx. 实体应该是从ProductEx继承的动态代理。
Is there a way to achive this? 有没有办法做到这一点?
One way is to You can create a wrapper for product: 一种方法是您可以为产品创建包装器:
public class Product
{
public virtual int ProductId { get; set; }
public virtual string Name { get; set; }
}
public class ProductEx : Product, ISomeInterface
{
private readonly Product _product;
public ProductEx(Product product) {
this._product = product;
}
public bool ISomeInterface.SomeMethod() { return false; }
public override int ProductId
{
get { return this._product.ProductId; }
set { this._product.ProductId = value; }
}
public override string Name
{
get { return this._product.Name; }
set { this._product.Name = value; }
}
}
Then you can query liko so: 然后,您可以查询liko:
var query = from p in context.Products
select new ProductEx(p);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.