I am working on a Windows Forms Application and I have several sql tables with the same structure but with different names. I wanted to use LINQ so I added Entity Framework to the project using NuGet and I am trying to do this with Entity Framework Code First.
First I setup a class for Timer
data. Each property has a matching column in each of the tables.
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();
}
}
Then I created a class where I could pass in the name of the table so I could return the table as a collection.
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; }
}
Then I want to be able to create the collections like this.
var currTimers = new TimerContext(currentReleaseTimerTableName).Timers.ToList();
var prevTimers = new TimerContext(previousReleaseTimerTableName).Timers.ToList();
I setup the app.Config file like this.
<connectionStrings>
<add name="fooDb" providerName="System.Data.sqlclient" connectionString="Data Source=10.0.0.25;Initial Catalog=foo;User ID=foouser;Password=foopass;" />
</connectionStrings>
I know this connection string works because I've been using it with other SQL commands, but when I try to use Entity Framework I keep getting the error Value cannot be null. Parameter name: source
Value cannot be null. Parameter name: source
when I call var currTimers = new TimerContext(currentReleaseTimerTableName).Timers.ToList();
.
I know the error says the source
is null, but what does it mean by source
? Where am I going wrong?
Timers is null because it wasn't set. It should be of type DbSet(of Timer).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.