为什么EntityFramework生成了DbContext?

时间:2013-06-24 08:42:55

标签: entity-framework

我先做数据库,EF已生成Code First DbContext子类......

//------------------------------------------------------------------------------
// <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 Glossary.UI.Database
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

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

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

        public DbSet<GlossaryTerm> GlossaryTerms { get; set; }
    }
}

正如你可以看到它抛出一个异常所以我需要在每次重新生成代码时对此进行评论!更重要的是,它为什么会产生这个类?

1 个答案:

答案 0 :(得分:3)

您需要一个上下文才能使用Entity Framework。您可以自己编写一个,也可以使用该工具自动生成它。对于使用数据库的较新版本的EF(.EDMX和设计器),它将自动为您生成DbContext。

您在上面显示的DbContext不是“Code First”上下文,因为它具有UnintentionalCodeFirstException。如果抛出该异常,则建议您trying to use code first mode.

检查数据库是否存在并检查连接字符串。 Don't use code first by mistake

相关问题