繁体   English   中英

实体框架代码的第一个例外:值不能为null。 参数名称:来源

[英]Entity Framework Code First Exception: Value cannot be null. Parameter name: source

我正在Windows窗体应用程序上工作,我有几个具有相同结构但名称不同的sql表。 我想使用LINQ,所以我使用NuGet将Entity Framework添加到项目中,而我尝试使用Entity Framework Code First来实现。

首先,我为Timer数据设置了一个类。 每个属性在每个表中都有一个匹配的列。

public class Timer
{
    public int id { get; set; }
    public DateTime Time { get; set; }
    public string Task { get; set; }
    public string ElapsedTime { get; set; }
    public string MachineName { get; set; }
    public int MachineId { get; set; }
    public string RunGuid { get; set; }
    public string Domain { get; set; }
    public string Area { get; set; }
    public double TotalMilliseconds { get; set; }
    public string ReleaseVersion { get; set; }
    public int NavigationProfileId { get; set; }

}
class Timers : IEnumerable<Timer>
{
    public List<Timer> TimerList { get; set; }

    public IEnumerator<Timer> GetEnumerator()
    {
        return TimerList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return TimerList.GetEnumerator();
    }
}

然后,我创建了一个类,可以在其中传递表名,以便可以将表作为集合返回。

public class TimerContext : DbContext
{
    private readonly string _tableName;

    public TimerContext(string tableName) : base("name=fooDb")
    {
        _tableName = tableName;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Timer>().ToTable(_tableName);

        base.OnModelCreating(modelBuilder);
    }

    public IEnumerable<Timer> Timers { get; set; }
}

然后,我希望能够创建这样的集合。

var currTimers = new TimerContext(currentReleaseTimerTableName).Timers.ToList();
var prevTimers = new TimerContext(previousReleaseTimerTableName).Timers.ToList();

我像这样设置app.Config文件。

<connectionStrings>
    <add name="fooDb" providerName="System.Data.sqlclient" connectionString="Data Source=10.0.0.25;Initial Catalog=foo;User ID=foouser;Password=foopass;" />
  </connectionStrings>

我知道此连接字符串有效,因为我已经将其与其他SQL命令一起使用,但是当我尝试使用实体框架时,我不断收到错误Value cannot be null. Parameter name: source Value cannot be null. Parameter name: source当我调用var currTimers = new TimerContext(currentReleaseTimerTableName).Timers.ToList();

我知道错误指出source为空,但是source意味着什么? 我要去哪里错了?

计时器为空,因为未设置。 它应该是DbSet(of Timer)类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM