i have a product manager application i'm trying to design using interfaces. a product can be 1 of 2 types Print or Online. i'd like to be able do the usual CRUD operations on it. i'm using Entity Framework but i came across a snag when building the interface.
For example I went to add my first method for the interface AddProduct(Product productToCreate). What type do I use for the Product since my entites are from Entity Framework? So I created an intermediate object call Product to transfer the Entity Framework object into it so it could fit in the interface. Is that right? Please advise.
class EFPrint
{
//Entity Framework object
public int PrintId { get; set; }
public string Product { get; set; }
public string Code { get; set; }
}
class EFOnline
{
//Entity Framework object
public int OnlineId { get; set; }
public string Product { get; set; }
public str开发者_开发百科ing Code { get; set; }
}
class Product
{
public int Id { get; set; }
public string Product { get; set; }
public string Code { get; set; }
}
interface IProductManagerService
{
void AddProduct(Product product);
}
class PrintService : IProductManagerService
{
public void AddProduct(Product product)
{
throw new NotImplementedException();
}
}
class OnlineService : IProductManagerService
{
public void AddProduct(Product product)
{
throw new NotImplementedException();
}
}
Entity Framework allows you to work with bases classes. You should create a base Product class, have the OnlineProduct and PrintProduct inherit from Product:
public class Product { ... }
public class Online : Product { ... }
public class Print : Product { ... }
In your DbContext, instead of having a DbSet for each type, you should have a single DbSet for Product, and just add accessors in order to retrieve only products from a specific type:
public class ProductsContext : DbContext
{
public DbSet<Product> Products { get; set; }
public IQueryable<Online> OnlineProducts
{
get
{
return Products.OfType<Online>();
}
}
public IQueryable<Print> PrintProducts
{
get
{
return Products.OfType<Print>();
}
}
}
精彩评论