gpt4 book ai didi

c# - Entity Framework 返回 0 项

转载 作者:太空狗 更新时间:2023-10-29 23:50:29 24 4
gpt4 key购买 nike

我正在使用 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/

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