c# - 基于没有键定义的类 mvc5

标签 c# asp.net-mvc asp.net-mvc-5

我尝试从这个 Controller 添加 View 。我只需要这个 View 来显示不用于插入或更新或删除的数据

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

然后我得到了这个错误:

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

    }
}

最佳答案

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

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

这会创建一个名为 Id 的新属性,[Key] 属性使其成为主键。从技术上讲,您不需要该属性,因为 EF 将选择 Id 属性并将其用作键,但我更愿意明确。

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

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

}

关于c# - 基于没有键定义的类 mvc5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909745/

相关文章:

c# - 如何使用 LINQ 生成数据透视数据?

javascript - 在 jQuery 对话框关闭之前不返回结果?

css - MVC5 - 导航栏事件颜色

asp.net - Application_AuthenticateRequest 命中所有请求,包括图片和js文件

c# - 如何使用刷新 token 更新访问 token ?

angularjs - AngularJS SPA 中推荐的身份验证 UX,带有自己的和外部(Google、FB ...)配置文件

c# - 尝试使用中继器填​​充表格

c# - 从 Xamarin PCL 调用 REST API 时程序挂起

c# - 使用 Lambda 表达式从多条记录中获取最大值

c# - HttpWebResponse 输出流不关闭