HamsterRoll
HamsterRoll

Reputation: 107

How do I write my first LINQ query using c# from scratch?

I checked many tutorials but none is helping me. I use EF 6 and .Net 4.5 Well I have class AccountsContext which has the following

public class AccountingContext : DbContext 
{
    public DbSet<Account> Accounts { get; set; }
    public DbSet<Transaction> Transactions { get; set; }
    public DbSet<TransactionType> TransactionTypes { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    }
}

and I am trying to call it from another class in the same namespace where i included

using Entity.Data;


List<Account> AccountsEntity = (from x in Accounts select x).ToList();
           account = (from acc in AccountsEntity
            where acc.AccountName == name 
            select acc).FirstOrDefault();

I keep getting that Accounts does not exist in the current context and I don't know what to do.

Upvotes: 0

Views: 59

Answers (1)

Eric J.
Eric J.

Reputation: 150108

You need a DbContext for your query, e.g.

using (AccountingContext ctx = new AccountingContext())
{
    List<Account> AccountsEntity = (from x in ctx.Accounts select x).ToList();
}

Note that List<Account> AccountsEntity should be List<Account> accountsEntity according to Microsoft's naming and casing conventions.

Upvotes: 1

Related Questions