首页 > 解决方案 > 捕获“指定的演员表无效。” 在 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

标签: c#asp.net-mvcentity-frameworkdbset

解决方案


您已将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;
        }
    }
}

推荐阅读