Based on class that has no key defined mvc5
asp.net-mvc, asp.net-mvc-5, c#
Solution
There are two options here. First, if this class is mapped to a table in your database, every model in entity framework requires a primary key. Add this into your model:
[Key]
public int Id { get; set; }
This creates a new property called `Id` and the `[Key]` attribute makes it a primary key. Technically you don't need the attribute as EF will pick up `Id` property and use it as a key, but I prefer to be explicit.
Alternatively, if you don't want this class to be a table in your database, add the `NotMapped` attribute to the class like this:
[NotMapped]
public class New
{
public List<Cart> CartItems { get; set; }
public decimal? CartTotal { get; set; }
}
Problem
I try to add view from this controller . I only need this view to show data not for insert or update or delete ``` public ActionResult Index() { var CartObj = ShoppingCart.GetCart(this.HttpContext); var classshop = new New { CartItems = CartObj.GetCartItems(), CartTotal = CartObj.GetSum() }; return View(classshop); } namespace MusicStore.Models { public class ShoppingCart { MusicStoreEntities dbo = new MusicStoreEntities(); string ShoppingCartID { get; set; } public const string CartSessionKey = "CartId"; public static ShoppingCart GetCart(HttpContextBase Context) { var cart = new ShoppingCart(); cart.ShoppingCartID = cart.GetCardId(Context); return cart; } public static ShoppingCart GetCart(Controller controller) { return GetCart(controller.HttpContext); } public List<Cart> GetCartItems() { return dbo.Carts.Where(a => a.CartId == ShoppingCartID).ToList(); } public decimal? GetSum() { decimal? Sum = (from items in dbo.Carts where items.CartId == ShoppingCartID select (int)items.Count * items.album.Price).Sum(); return Sum ?? decimal.Zero; } } } ``` and then I got this error: there was an error running the selected code generator: 'unable to retrieve metadata for 'Musicstore.Model.new' one or more validation error were detected during model generation musicstore,models.New :entity type'New' has no key defined . define the key of entityType ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MusicStore.Models { public class New { public List<Cart> CartItems { get; set; } public decimal? CartTotal { get; set; } } } ```