c# - Entity Framework 返回 0 项

标签 c# entity-framework-6

我正在使用 Entity Framework 6.1.3。

当我尝试从数据库表中获取值时,它返回 0 个项目,但在数据库中是 9 行。

Entity FrameWork 调用 OnModelCreating 方法。

我搜索了整个互联网,但没有找到解决方法。

我的 DbContext 类

namespace TestTask.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class Entities : DbContext
    {
        public Entities()
            : base("MenuItemsContainer")
        { }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) 
        { 

        modelBuilder.Properties() 
                    .Where(p => p.Name == "Id") 
                    .Configure(p => p.IsKey()); 
        } 

        public virtual DbSet<DataMenuItemSet> DataMenuItemSet { get; set; }
        public virtual DbSet<ItemsSet> ItemsSet { get; set; }
    }
}

我的 DataMenuItemSet 类

using System.ComponentModel.DataAnnotations;

namespace TestTask.Models
{
    using System;
    using System.Collections.Generic;

    public partial class DataMenuItemSet
    {
        public DataMenuItemSet()
        {
            this.ItemsSet = new HashSet<ItemsSet>();
        }

        [Key]
        public int Id { get; set; }
        public bool IsRoot { get; set; }
        public string Name { get; set; }
        public Nullable<int> Parent { get; set; }

        public virtual ICollection<ItemsSet> ItemsSet { get; set; }
    }
}

所有这些都是用 Entity Framework 生成的。

我需要从数据库中获取值。

已更新

我已经解决了这个问题。

重点是我的解决方案中有两个项目。第一个是一个站点,它有来自数据库的模型,第二个是简单的 ConsoleApplication,我试图在其中测试数据库数据。当我尝试通过 dbcontext 从其他应用程序连接到 db 时,它无法如上所述工作。为了让它工作,我将一个连接字符串从具有 edmx 模型和 dbcontext 的网站应用程序传输到我正在测试此连接和数据的应用程序。

这是它的工作原理

enter image description here

黄色 - ConsoleApplication 红色 - 带有模型和 dbcontext 的网站

enter image description here

这是一个模型和Web.config 我将连接字符串从 Web.config 转移到 ConsoleApplication 的 App.cofig 和模型。

enter image description here

带有传输模型和连接字符串的 ConsoleApplication。

毕竟它对我有用。

感谢帮助!!!

最佳答案

这是使用 Entity Framework 和 LINQ 查询从数据库中获取数据的非常常见的方法。

using (var context = new Entities())
{
    var L2EQuery = from item in context.DataMenuItemSet
                   where item.IsRoot == true
                   select item;

    var result = L2EQuery.ToList()<DataMenuItemSet>;
 }

希望对您有所帮助。

关于c# - Entity Framework 返回 0 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31628304/

相关文章:

c# - 正则表达式问题,将数据提取到组

design-patterns - Entity Framework 实体包装器接口(interface)背后采用哪种设计模式?

c# - 将实体映射到 DTO,无需重复代码

c# - EF 不包括外键使用外类型的最后一个对象

c# - 如何获取 OPC 服务器上的标签列表

c# - 编辑完单元格后自动对 DataGridView 进行排序

c# - 从自定义 header 中检索访问 token

c# - Entity Framework - ConnectionProviderName 的更新数据库命令提示

entity-framework - EF6 Code First - 使用不匹配的外键配置一对一关系

c# - XAML/WPF 缩放到 Canvas 上的特定区域