簡體   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