gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:59:14 25 4
gpt4 key购买 nike

我尝试从这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com