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

本文关键字:null 参数 不能 代码 框架 第一个 实体 | 更新日期: 2023-09-27 18:31:19

我正在开发一个Windows窗体应用程序,我有几个结构相同但名称不同的sql表。我想使用 LINQ,因此我使用 NuGet 将实体框架添加到项目中,并且我正在尝试首先使用实体框架代码执行此操作。

首先,我为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();

我设置了应用程序。像这样的配置文件。

<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 命令一起使用它,但是当我尝试使用实体框架时,当我调用 var currTimers = new TimerContext(currentReleaseTimerTableName).Timers.ToList(); 时,我不断收到错误Value cannot be null. Parameter name: source

我知道错误说source为空,但source是什么意思?我哪里出错了?

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

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