实体框架 RC1 DbContext 查询问题

发布于 2024-10-22 02:51:17 字数 2411 浏览 1 评论 0原文

我正在尝试首先使用实体​​框架代码 rc 1 来实现存储库模式。我遇到的问题是创建 DbContext。我有一个解析 IRepository 的 ioc 容器,它有一个 contextprovider,它只是在 Windsor.config 文件中使用连接字符串更新一个新的 DbContext。对于 linq2sql,这部分没有问题,但 EF 似乎令人窒息。下面我将通过一个例子来描述这个问题。我已经提取了代码来简化一些事情,这就是为什么您在这里看不到任何存储库模式的内容。只是排序正在发生的事情,而无需所有额外的代码和类。

            using (var context = new PlssContext())
            {
                var x = context.Set<User>();
                var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault();
            }

            using (var context2 = new DbContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=PLSS.Models.PlssContext;Integrated Security=True;MultipleActiveResultSets=True"))
            {
                var x = context2.Set<User>();
                var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault();
            }

PlssContext 是我创建 DbContext 类的地方。存储库模式对 PlssContext 一无所知。我认为我能做的最好的事情就是使用 sqlexpress 数据库的连接字符串创建一个 DbContext 并以这种方式查询数据。 var context2 中的连接字符串是在更新 PlssContext 对象后从上下文中获取的。所以他们指向同一个 sqlexpress 数据库。

第一个查询有效。第二个查询严重失败并出现以下错误:

支持“DbContext”的模型 自数据库以来上下文已更改 被创建。要么手动 删除/更新数据库,或调用 Database.SetInitializer 具有 IDatabaseInitializer 实例。为了 例如, 如果模型更改则删除创建数据库 策略会自动删除和 重新创建数据库,并且可以选择 用新数据播种。

在这一行上,

var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault();

这是我的 DbContext

namespace PLSS.Models
{
    public class PlssContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Corner> Corners { get; set; }
        public DbSet<Lookup_County> Lookup_County { get; set; }
        public DbSet<Lookup_Accuracy> Lookup_Accuracy { get; set; }
        public DbSet<Lookup_MonumentStatus> Lookup_MonumentStatus { get; set; }
        public DbSet<Lookup_CoordinateSystem> Lookup_CoordinateSystem { get; set; }

        public class Initializer : DropCreateDatabaseAlways<PlssContext>
        {
            protected override void Seed(PlssContext context)
            {

我已经尝试了所有初始化策略,但出现了相同的错误。我不认为数据库正在改变。如果我删除

     modelBuilder.Conventions.Remove<IncludeMetadataConvention>();

那么错误返回的是

实体类型 User 不是当前上下文模型的一部分。

哪一种有道理。但如何将这一切整合在一起呢?

I'm trying to implement the repository pattern using entity framework code first rc 1. The problem I am running into is with creating the DbContext. I have an ioc container resolving the IRepository and it has a contextprovider which just news up a new DbContext with a connection string in a windsor.config file. With linq2sql this part was no problem but EF seems to be choking. I'll describe the problem below with an example. I've pulled out the code to simplify things a bit so that is why you don't see any repository pattern stuff here. just sorta what is happening without all the extra code and classes.

            using (var context = new PlssContext())
            {
                var x = context.Set<User>();
                var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault();
            }

            using (var context2 = new DbContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=PLSS.Models.PlssContext;Integrated Security=True;MultipleActiveResultSets=True"))
            {
                var x = context2.Set<User>();
                var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault();
            }

PlssContext is where I am creating my DbContext class. The repository pattern doesn't know anything about PlssContext. The best I thought I could do was create a DbContext with the connection string to the sqlexpress database and query the data that way. The connection string in the var context2 was grabbed from the context after newing up the PlssContext object. So they are pointing at the same sqlexpress database.

The first query works. The second query fails miserably with this error:

The model backing the 'DbContext'
context has changed since the database
was created. Either manually
delete/update the database, or call
Database.SetInitializer with an
IDatabaseInitializer instance. For
example, the
DropCreateDatabaseIfModelChanges
strategy will automatically delete and
recreate the database, and optionally
seed it with new data.

on this line

var y = x.Where(u => u.UserName == LogOnModel.UserName).FirstOrDefault();

Here is my DbContext

namespace PLSS.Models
{
    public class PlssContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Corner> Corners { get; set; }
        public DbSet<Lookup_County> Lookup_County { get; set; }
        public DbSet<Lookup_Accuracy> Lookup_Accuracy { get; set; }
        public DbSet<Lookup_MonumentStatus> Lookup_MonumentStatus { get; set; }
        public DbSet<Lookup_CoordinateSystem> Lookup_CoordinateSystem { get; set; }

        public class Initializer : DropCreateDatabaseAlways<PlssContext>
        {
            protected override void Seed(PlssContext context)
            {

I've tried all of the Initializer strategies with the same errors. I don't think the database is changing. If I remove the

     modelBuilder.Conventions.Remove<IncludeMetadataConvention>();

Then the error returns is

The entity type User is not part of the model for the current context.

Which sort of makes sense. But how do you bring this all together?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哭泣的笑容 2024-10-29 02:51:17

这是正确的行为。普通的DbContext不知道映射(=不知道您的任何实体)。这就是为什么您应该始终创建派生上下文的原因。您的存储库不知道 PlssContext,但您仍然可以像这样注入它:

public class Repository
{
  private readonly DbContext _context;

  public Repository(DbContext context)
  {
    _context = context;
  }
  ...
}

var repository = new Repository(new PlssContext());

首先使用代码时,不能直接使用基本 DbContext 实例。

That is correct behavior. Plain DbContext has no idea about mappings (= doesn't know any of your entities). That is the reason why you should always create derived context. Your repository doesn't know about PlssContext but you can still inject it like:

public class Repository
{
  private readonly DbContext _context;

  public Repository(DbContext context)
  {
    _context = context;
  }
  ...
}

var repository = new Repository(new PlssContext());

You can't use base DbContext instance directly when using code first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文