c# - 类库中的 Entity Framework 代码优先

标签 c# .net entity-framework-4 entity-framework-4.1

今天早上我刚开始尝试 EF4 代码,我在一个单独的类库中创建了我的 POCO、数据上下文和初始化程序类,我相信这是常规的样板代码。我在 MVC3 应用程序中引用该类,并在 Global.asax 中设置初始化程序。在运行应用程序时,我注意到以下问题
1. 没有在任何地方创建数据库(然后我在 web.config 中添加了一个以 Context 类命名的连接字符串的条目,仍然没有结果)
2. 当我尝试访问初始化值时,出现空错误,显然是因为没有数据。

谁能帮我指点一下如何让它工作(如果我整个圣诞节都在学习这个,但我仍然无法让它工作,那将是一种耻辱:( ) 谢谢
附:我尝试插入断点并点击了应用程序初始化方法,但它从未点击初始化程序中的 Seed 方法,即使我也在那里添加了一个断点!
谢谢。
初始化类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;
    using F2AController.Models;

    namespace F2AController.DataObjects
    {
        public class F2AInitializer : DropCreateDatabaseAlways<F2AContext>
        {
            protected override void Seed(F2AContext context)
            {
                var countries = new List<Country> 
                {
                    new Country(){ CountryName="Germany", Active = true},
                    new Country(){ CountryName="Britain", Active = true}
                };
                countries.ForEach(s => context.Countries.Add(s));
                context.SaveChanges();
                var providers = new List<Providers>() 
                {
                    new Providers(){ ProviderName="InfoBip", ContactDetails="Rturo Manovic", Active=true, MessageRates= new List<ProviderRates>(){new ProviderRates(){ CountryId=1, DateCreated=DateTime.Now, DateModified=DateTime.Now, Rate=0.05M, Active=true}}}
                };
                providers.ForEach(p => context.Providers.Add(p));
                context.SaveChanges();
                var usermobiles = new List<MobileTerminal>()
                {
                    new MobileTerminal(){ Active= true, Credits=200, DateCreated=DateTime.Now, MSISDN="4477565444865"}
                };
                usermobiles.ForEach(u => context.MobileTerminals.Add(u));

                context.SaveChanges();
            }


        }
    }

上下文类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace F2AController.Models
{
    public class F2AContext : DbContext
    {
        public DbSet<Country> Countries;
        public DbSet<MobileTerminal> MobileTerminals;
        public DbSet<Providers> Providers;
        public DbSet<ProviderRates> ProviderRates;
        public DbSet<Property> Properties;
        public DbSet<ShortMessage> ShortMessages;
        public DbSet<UserProperties> UserProperties;

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}

Global.asax App初始化方法

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Database.DefaultConnectionFactory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["F2AContext"].ConnectionString);
        Database.SetInitializer<F2AContext>(new F2AInitializer());

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

最佳答案

终于找到了!
在寻找解决方案时,我遇到了这篇文章 Entity Framework Database.SetInitializer simply not working
应用那里建议的解决方案以强制我的数据库像我预期的那样在启动时创建工作,但随后在运行种子代码时,它抛出了一个空指针异常。在调查时,我意识到任何从 Context 类引用 DBSet 集合的尝试都会产生相同的异常。进一步检查我意识到,而不是使用

 public DbSet<MobileTerminal> MobileTerminals { get; set; }

我用过

   public DbSet<MobileTerminal> MobileTerminals;

这意味着我没有得到任何隐式对象初始化,因此空指针异常。我删除了强制初始化代码并再次运行应用程序,这次种子代码没有运行,直到我访问了一个实际查询数据上下文的页面并且它运行完美。
显然,由于延迟加载,初始化代码直到实际需要时才会运行,即第一次在应用程序中查询数据上下文。

我希望这对以后遇到同样问题的人有所帮助。

关于c# - 类库中的 Entity Framework 代码优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631089/

相关文章:

C# MongoDb 驱动问题 Update Failing

c# - 为关闭计算机而创建的 Windows 服务在计算机锁定时无法运行

.net - 适用于 Linux 的 ASP.NET 页面设计器

entity-framework-4 - 删除/更新多对多 Entity Framework 。无法让它工作

c# - 使用 GridSplitter 调整网格大小

c# - 一点点弦乐 Actor

c# - 为什么 C# 7.2 中的 Pinnable<T> 类是这样定义的?

c# - Entity Framework 错误 : AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager

c# - 使用 Entity Framework 的输出参数执行 SQL 存储过程

c# - MVC 验证 - 更新另一个字段?