I created a class Cartline. Then I created a collection called ShoppingCart. When I try to declare ShoppingCart, I receive error. Does anyone know to fix this?
public class CartLine
{
public int CartLineId { get; set; }
public Product Product { get; set; }
public int Quantity { get; set; }
}
using ShoppingCart = System.Collections.Generic.IEnumerable<ElectronicsStore.Models.CartLine>;
ShoppingCart shoppingcart = new ShoppingCart();
Cannot create an instance of the abstract class or interface 'IEnumerable<CartLine>' ElectronicsStore
The easiest solution is to creating a new class called ShoppingCart that has a property which is a List of CartLine entities:
public class CartLine
{
public int CartLineId { get; set; }
public Product Product { get; set; }
public int Quantity { get; set; }
}
public class ShoppingCart
{
public IList<CartLine> CartLines {get;set;}
}
ShoppingCart shoppingcart = new ShoppingCart();
The error is self explanatory. Two options - you can create an alias using a concrete type (eg List<CartLine>
) but, instead, I'd recommend you define a class that inherits from List<CartLine>
(or whatever collection best suits your needs):
public class ShoppingCart : List<CartLine>
{
// implement constructors you want available
public ShoppingCart(){}
public ShoppingCart( IEnumerable<CartLine> collection ) : base( collection ) {}
public ShoppingCart( int capacity ) : base( capacity ) {}
// the benefit here is you can add useful properties
// if CartLine had a price you could add a Total property, for example:
public decimal Total => this.Sum( cl => cl.Quantity * cl.Price );
}
Then you may use as requested:
var cart = new ShoppingCart();
cart.Add( new CartLine() { ... } );
var cartTotal = cart.Total;
... etc ...
Collection initializer will also work:
var cart = new ShoppingCart() { new CartLine() { ... }, ... }
Or initialize with existing IEnumerable<CartLine>
, eg an IQueryable<CartLine>
using Entity Framework:
var cart = new ShoppingCart( dbContext.CartLines.Where( ... ) );
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.