c# - 使用 Entity Framework 时出现数据库错误

标签 c# database visual-studio entity-framework

我要实现的目标非常简单。我只想拥有一个本地数据库文件,我可以使用 Entity Framework 从中显示 ListView 中的记录。问题是,每次构建它时,我都会收到此错误:

'DiaryEntities' does not contain a definition for 'Title' and no extension method 'Title' accepting a first argument of type 'DiaryEntities' could be found (are you missing a using directive or an assembly reference?)

我的数据库名为 Diary,我只有一个名为 Entries 的表,其中包含列 TitleDate内容。这是我的文件:

//main.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace diary
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (diary.DiaryEntities de = new DiaryEntities())
            {
                var diaries = (from m in de.Diary select m.Title);
                listBox1.Items.AddRange(diaries.ToArray());
            }
        }
    }
}

//DiaryEntities.Context.cs
namespace jurnal1
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class DiaryEntities : DbContext
    {
        public DiaryEntities() : base("name=DiaryEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<DiaryEntities>Diary { get; set; }
    }
}

最佳答案

将您的代码更改为:

namespace jurnal1 {
        using System;
        using System.Data.Entity;
        using System.Data.Entity.Infrastructure;
        using System.ComponentModel.DataAnnotations.Schema;

        public partial class DiaryEntities : DbContext {

            public DiaryEntities ( )
                : base ( "name=DiaryEntities" ) {
            }

            protected override void OnModelCreating ( DbModelBuilder modelBuilder ) {

            }
            public DbSet<Entries> Diary { get; set; }

        }

        [Table("entries")]
        public class Entries {
            public int Id { get; set; }
            public string Title { get; set; }
            public DateTime Date { get; set; }
            public string Content { get; set; }
        }
    }
}

check the GITHUB project我试试这个,我认为问题是:模型需要一个键,所以,添加一个 id,我认为你的数据库表有更多列,请尝试链接上的项目。

关于c# - 使用 Entity Framework 时出现数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003713/

相关文章:

c# - 从 SignalR Hub 类中重定向用户

C# 方法重载和泛型接口(interface)

c# - 生成 WPF 窗口的屏幕截图

python - 许多数据库查询或复杂的逻辑?

c# - 通过本地项目引用导入 NuGet 引用

c# - List<String> ByRef

mysql - 检索数据的最佳实践? SQL 数据库与 HTML 解析

database - SQL 插入错误 : Cannot insert the value NULL into column 'Id'

visual-studio - 无法在 Visual Studio 2022 中重新打开 MAUI 项目(非预览版)

c - 释放二维数组 - 检测到堆损坏