ktom February 2016

How can I use context in Entity Framework?

I made Entity models in MVC, in model first approach, and I would like to know, how to insert, delete, and modify data.

I try to use

namespace EntityFrameworkModelFirst
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class ModelFirstContainer : DbContext
    {
        public ModelFirstContainer()
            : base("name=ModelFirstContainer")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();

        }

        public virtual DbSet<Department> DepartmentSet { get; set; }
        public virtual DbSet<Employee> EmployeeSet { get; set; }
    }

    using (var context = new ModelFirstContainer()) 
    {     
    // Perform data access using the context 
    }

}

But, it makes error to me. The error is: The contextual word 'var' may only appear within a local variable declaration or in script code, and missing ;. Is it valid now? Where can i do this? Which files?

Thank you

Answers


Georg Patscheider February 2016

A tutorial on how to work with the Entity Framework DbContext can be found here: Working with DbContext

    public class ProductContext : DbContext 
{ 
    public DbSet<Category> Categories { get; set; } 
    public DbSet<Product> Products { get; set; } 
}

using (var context = new ProductContext()) 
{     
    // Perform data access using the context 
}


mason February 2016

Your using block must be in a method. You can't have it outside of a method. Also, I've removed your OnModelCreating which would have thrown an exception.

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace EntityFrameworkModelFirst
{   
    public partial class ModelFirstContainer : DbContext
    {
        public ModelFirstContainer() : base("name=ModelFirstContainer")
        {
        }

        public virtual DbSet<Department> DepartmentSet { get; set; }
        public virtual DbSet<Employee> EmployeeSet { get; set; }
    }

    public class SomeClass
    {
        public void DoSomeStuff()
        {
             using (var context = new ModelFirstContainer()) 
             {     
                 // Perform data access using the context 
             }
        }
    }
}

A using block is used with IDisposable objects to ensure they get properly disposed. ModelFirstContainer inherits from DbContext which implements IDisposable.

Post Status

Asked in February 2016
Viewed 3,893 times
Voted 14
Answered 2 times

Search




Leave an answer