实体框架代码第一个例外:值不能为空。参数名称:source

时间:2014-11-20 03:17:27

标签: c# linq entity-framework

我正在使用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时不断收到错误var currTimers = new TimerContext(currentReleaseTimerTableName).Timers.ToList();

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

1 个答案:

答案 0 :(得分:1)

定时器为空,因为它没有设置。它应该是DbSet(定时器)类型。