c# - 捕获“指定的演员表无效。” 在 C# ASP.net MVC 中接收数据时出错?
问题描述
我是实体框架的新手。我试图通过这个基本的代码行从我的本地数据库中获取我的数据,我想将“对象”行中的所有对象存储到一个列表中。
但它似乎不起作用,无论我尝试什么。我正在运行 SQL 服务器、ASP.NET MVC。我的代码是这样的:
[HttpGet]
public List<Object> Function1()
{
List<Object> result = new List<Object>();
using (DatabaseContext db = new DatabaseContext())
{
result = db.Object.ToList();
// ...
return result;
}
}
这是捕获错误的地方:
第 137 行:结果 = db.Object.ToList();
这是我的模型类,虽然我添加了一些功能,但我没有更改 Entity 为我设置的任何默认属性:
public partial class Object
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public int Like { get; set; }
public int View { get; set; }
public byte Level
{
get { return Level; }
set
{
if (value < 1 || value > 3)
{
Level = 1;
throw new Exception("Level must be in 1 to 3. By default, it becomes 1");
}
else
{
Level = value;
}
}
}
public string Introduction { get; set; }
public string VideoUrl { get; set; }
public string Tag { get; set; }
public string Steps { get; set; }
public DateTime Date { get; set; }
public Object(string name, byte level, string introduction = null)
{
this.Name = name;
this.Level = level;
this.Introduction = introduction;
}
}
可以添加功能并修复这样的属性吗?
这是我在 sql 中的表设计:pic
解决方案
您已将public byte Level
自动属性与自定义setter
方法一起使用。
这应该伴随一个私有的支持变量。就像是
private byte _level
public byte Level
{
get { return _level; }
set
{
if (value < 1 || value > 3)
{
_level = 1;
throw new Exception("Level must be in 1 to 3. By default, it becomes 1");
}
else
{
_level = value;
}
}
}
推荐阅读
- java - 如何知道Java中哪个引用是静态的
- python - 如何编码我的不和谐机器人,以便它可以在用户设备上执行谷歌搜索?
- amazon-web-services - AWS sts 在一个命令中扮演角色
- oauth-2.0 - OAuth2.0 [PKCE] Flow failing between LinkedIn and Forgerock
- python-3.x - 我应该在哪里放置一个在 Django 中填充我的数据库的 Python 脚本?
- javascript - 如何开始创建 Web 服务?webix+js+revel
- python - 如何在不使用 discord.py 中的列表的情况下永久存储用户数据?
- excel - 选择列并应用格式
- python - python中getch的箭头键
- aws-sam - 适用于 VS Code SAM 本地代码的 AWS 工具包无法正常工作