Reputation: 7818
I am getting the following syntax error in my console app:
An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.db'
How can I fix this? I've read suggestions about making db
static, but I don't fully understand that.
class Program
{
private CallContext db = new CallContext();
private BreachContext bc = new BreachContext();
static void Main(string[] args)
{
var snapshot = db.Calls.Where(x => x.team == "T1").ToList();
Upvotes: 0
Views: 3021
Reputation: 13531
I assume you have a good reason to make it a global variable (maybe you use it in other operations too), so if you really want this, the db declaration should be static too:
private static CallContext db = new CallContext();
Reason: you are using the non-static db
variable in a static Main
method, which is not possible.
However, if there is no reason to make it global and static, you can also put the declaration and initialization in the Main method itself and then use it. I assume that CallContext
is an Entity Framework context, so in that case use the using
statement to dispose it after usage:
static void Main(string[] args)
{
using (var db = new CallContext())
{
var snapshot = db.Calls.Where(x => x.team == "T1").ToList();
}
}
Upvotes: 1
Reputation: 66449
You're creating an instance of CallContext
, but only when you create an instance of Program
.
However, Main
is static and doesn't require an instance of Program
, so db
is not instantiated when Main
runs.
I'd just instantiate it inside Main, when you need it. If it's disposable, you might consider wrapping it in a using
statement as well.
static void Main(string[] args)
{
var db = new CallContext();
var snapshot = db.Calls.Where(x => x.team == "T1").ToList();
Upvotes: 6