Category Archives: Entity Framework

Entity Framework Scaffold DBContext (ASP.NET Core)

Steps:

– Install EF:

Install-Package Microsoft.EntityFrameworkCore.SqlServer

Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

– Add to project.json

 "tools": {
   "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final",
   "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
   "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
 },

– From “NuGet Package Manager” then “Package Manager Console”

Scaffold-DbContext "Server=;Database=;user id=;password=;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

– Update appsettings.json to include the connection string..

  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=devsql01;Database=nasr_scratch;user id=dev;password=Automation15;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=False;"
    } 
  },

– Add the DbContext to the Startup.cs using the connection string..

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.            
            services.AddMvc();
            services.AddDbContext(
                o => o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

Update the Context:

public class MyContext : DbContext
{
    public MyContext(DbContextOptions options)
      :base(options)
    { }
}

– Create your controller. For Instance; BulkTagCreationController. You can now reference the context using DI.

    [Route("api/configuration/[controller]")]
    public class BulkTagCreationController : Controller         
    {
        public readonly nasr_scratchContext _context;

        public BulkTagCreationController(nasr_scratchContext context)
        {
            _context = context;
        }

Apply Changes Made to a Detached Object

This allows changes to be stored based on the original object and changed object:

See:  https://msdn.microsoft.com/en-us/library/vstudio/bb896248%28v=vs.100%29.aspx

private static void ApplyItemUpdates(SalesOrderDetail originalItem,
SalesOrderDetail updatedItem)
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
context.SalesOrderDetails.Attach(updatedItem);
// Check if the ID is 0, if it is the item is new.
// In this case we need to chage the state to Added.
if (updatedItem.SalesOrderDetailID == 0)
{
// Because the ID is generated by the database we do not need to
// set updatedItem.SalesOrderDetailID.
context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
}
else
{
// If the SalesOrderDetailID is not 0, then the item is not new
// and needs to be updated. Because we already added the
// updated object to the context we need to apply the original values.
// If we attached originalItem to the context
// we would need to apply the current values:
// context.ApplyCurrentValues(“SalesOrderDetails”, updatedItem);
// Applying current or original values, changes the state
// of the attached object to Modified.
context.ApplyOriginalValues(“SalesOrderDetails”, originalItem);
}
context.SaveChanges();
}
}