【问题标题】:What am I supposed to do with this generated DbContext?我应该用这个生成的 DbContext 做什么?
【发布时间】:2016-10-31 02:14:42
【问题描述】:

我在我的数据库上使用了 Entity 的代码生成工具,它为我提供了上下文

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

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

    public partial class LRC_VAULTEntities : DbContext
    {
        public LRC_VAULTEntities()
            : base("name=LRC_VAULTEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Post> Posts { get; set; }
        public virtual DbSet<Thread> Threads { get; set; }
    }
}

我希望能够像这样立即使用它

var context = new LRC_VAULTENtities();
context.Posts.InsertOnSubmit(new Post() { ... });
context.Posts.SubmitChanges();

但是,在我创建了RC_VAULTENtities 的实例后,没有Posts 属性。那我该怎么办?

【问题讨论】:

  • 看起来像 LRC_VAULTEntitiesLRC_VAULTENtities 之间的拼写错误,因为代码显示 DbContext 中存在 Posts 属性
  • @Nkosi,不,这不是问题
  • @DeadlyNicotine 好吧,某处有一个错字——因为这根本不一定与 EF 有关。您已将 Posts 明确声明为属性,因此您几乎肯定引用了错误的类。
  • @Rob 我在我的实例上做了“转到定义”,这把我带到了我上面粘贴的类
  • 如果您只是尝试实例化上下文并运行调试会话,您会收到任何错误吗?有没有上下文可用的属性?

标签: c# asp.net asp.net-mvc entity-framework linq


【解决方案1】:

使用Base 类并添加对您的项目的引用,以便您可以在任何地方调用dbContext

public class Base
    {
        protected internal LRC_VAULTEntities dbContext;

        public Base()
        {
            dbContext = new LRC_VAULTEntities ();
        }
    }

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2021-03-24
    • 2012-11-13
    • 1970-01-01
    • 2022-01-19
    • 2022-06-11
    相关资源
    最近更新 更多