基于没有键定义mvc5的类

我尝试从这个控制器添加视图。 我只需要这个视图来显示不是插入或更新或删除的数据

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 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; } } } 

然后我收到了这个错误:

运行所选代码生成器时出错:’无法检索’Musicstore.Model.new’的元数据在模型生成musicstore,models期间检测到一个或多个validation错误。新:实体类型’New’没有定义键。 定义entityType的键

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MusicStore.Models { public class New { public List CartItems { get; set; } public decimal? CartTotal { get; set; } } } 

这里有两种选择。 首先,如果此类映射到数据库中的表,则entity framework中的每个模型都需要一个主键。 将其添加到您的模型中:

 [Key] public int Id { get; set; } 

这将创建一个名为Id的新属性, [Key]属性使其成为主键。 从技术上讲,你不需要属性,因为EF将获取Id属性并将其用作键,但我更喜欢明确。

或者,如果您不希望此类成为数据库中的表,请将NotMapped属性添加到类中,如下所示:

 [NotMapped] public class New { public List CartItems { get; set; } public decimal? CartTotal { get; set; } } 

我知道这是旧的,但我刚遇到这个问题。

当我在Models文件夹中创建一个类CreateEmployeeViewModel时,会发生什么?Visual Studio“聪明地”在我的数据库上下文类中添加了一行

 public System.Data.Entity.DbSet CreateEmployeeViewModels { get; set; } 

因此,在下次update-migration时创建了一个表。 删除此行删除了对关键字段的要求。

注意 :您可能还需要添加行AutomaticMigrationDataLossAllowed = true; 如果表已创建,则为DBMigrationConfiguration类。