【问题标题】:.NET - Is there a DbSet Find method in Microsoft.Data.Entity? [duplicate].NET - Microsoft.Data.Entity 中是否有 DbSet Find 方法? [复制]
【发布时间】:2016-03-28 04:52:15
【问题描述】:

我正在使用 ASP.NET MVC 5 创建一个 MVC 应用程序,它使用实体框架来处理数据库。

这是一个简单的应用程序,具有 CRUD 功能,可以将项目添加到带有数据库的列表中。我可以创建项目并将它们保存到数据库中,现在我想查看特定项目的页面。

我在以前的应用程序中使用DbSet 对象上的Find 方法完成了此操作,但该方法是System.Data.Entity 的一部分。我能够以这种方式创建应用程序,但使用 ASP.NET 5,我似乎需要以不同方式配置数据库连接,使用 Startup.cs 中的这些行:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

        services.AddMvc();
    }

这要求我使用Microsoft.Data.Entity 而不是System.Data.Entity

这是MyDbContext 类:

public class MyDbContext : DbContext
{

    public virtual DbSet<TestModel> TestModels { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=EmptyMVCAuthentication01;integrated security=True;");
    }
}

我希望查看特定页面的操作执行以下操作:

    public IActionResult Details(int id)
    {
        Course course= db.Courses.Find(id);
        return View(course);
    }

(上面的dbMyDbContext的私有实例)

但是,Microsoft.Data.Entity 中没有 Find 方法。关于我可以从这里去哪里的任何建议?

【问题讨论】:

标签: c# sql-server asp.net-mvc entity-framework asp.net-mvc-5


【解决方案1】:

Find() 方法在新版本的实体框架中不存在(截至今天的 EF 7)。根据 github issue 页面,他们将此添加到他们的积压中,因为很多人都在请求 FindFindAsync 方法。所以这可能会在未来的版本中提供。

目前,您可以根据需要使用FirstOrDefault()

public IActionResult Details(int id)
{
    var course= db.Courses.FirstOrDefault(d=>d.Id==id);
    if(course==null)
    {
      return View("NotFound");
    }
    return View(course);
}

假设 Id 是您的 Course 模型的主键。

有一些解决方法,例如按照here 所述编写扩展方法。但我更喜欢FirstOrDefault()FirstOrDefaultAsync(),因为它们给了我想要的东西。

【讨论】:

    猜你喜欢
    • 2015-05-15
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多