EntityFramework 6 Add-Migration with wrong placement of usings statement - entity-framework

We maintain an EF 6 project but I realized that Adding a new migration always generate the files like this which gives an error
namespace App.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddViews : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
instead of like this
using System;
using System.Data.Entity.Migrations;
namespace App.Data.Migrations
{
public partial class AddViews : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
I am using VS 2019 and I can't tell why I need to be moving it everytime

Related

How can I Insert data from code to Db and create POST method

Entity framework
I have to insert the data from code to Db and I have to create POST method. For this I have made the Employee controller but I am getting some error in code. This is my code:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VENUS.HRMS.DATA.Models;
namespace VENUS.HRMS.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
[HttpPost]
public TblEmployee InsertTblEmployee(TblEmployee _tblemployee)
{
using (TblEmployeesEntities entities = new TblEmployeesEntities())
{
entities.TblEmployees.Add(_tblemployee);
entities.SaveChanges();
}
return _tblemployee;
}
}
}
I am getting error on TblEmployeesEntities entities = new TblEmployeesEntities.
Please help me out.
I guess this sample code could help you. Write your DBcontext like below:
public partial class TblEmployeesEntities : DbContext
{
public TblEmployeesEntities ()
{ }
public TblEmployeesEntities (DbContextOptions<TblEmployeesEntities> options)
: base(options)
{ }
public virtual DbSet<TblEmployee> TblEmployees{ get; set; }
}
Then it's time to inject dbcontext in the startup if your DBMS is SQL server.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TblEmployeesEntities >(options =>
options.UseSqlServer("ConnectionString"));
}
Now just create a constructor in the controller and use DbContext:
private readonly TblEmployeesEntities _context;
public EmployeeController (TblEmployeesEntities context)
{
_context = context;
}
[HttpPost]
public TblEmployee InsertTblEmployee(TblEmployee _tblemployee)
{
_context.TblEmployees.Add(_tblemployee);
_context.SaveChanges();
return _tblemployee;
}

No extension Method ToList on a dbset - really though?

Background - I am using Entity framework code version 2.1.4-rtm-31024
check out the CODE LISTING 1 - the problem (according to Ms Build Engine 15.9) is that GetAllMakes calls .ToList, but no 'ToList' method exists for a DbSet of VehicleMake. (check out Code Listing 2) to see the implementation of _vehicleContext.VehicleMakes
Why do I get a compile error? this makes no sense to me since I can call VehicleMakes.ToList() elsewhere in the code (no compiler error) no problem at all - see listing 3 for an example.
CODE LISTING 1
using System.Collections.Generic;
namespace CarPriceComparison.Models
{
public class VehicleRepository : IVehicleRepository
{
private VehicleContext _vehicleContext;
public VehicleRepository(VehicleContext dbContext_)
{
_vehicleContext = dbContext_;
}
public IEnumerable<VehicleMake> GetAllMakes()
{
return _vehicleContext.VehicleMakes.ToList();
}
}
}
CODE LISTING 2
namespace CarPriceComparison.Models
{
public class VehicleContext : DbContext
{
private IConfigurationRoot _config;
public VehicleContext(IConfigurationRoot config_, DbContextOptions
options_) : base(options_)
{
_config = config_;
}
public DbSet<VehicleMake> VehicleMakes {get; set;}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:VehicleContextConnection"]);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleModel>()
.HasOne(p => p.Make)
.WithMany(b => b.Models)
.HasForeignKey(p => p.VehicleMakeForeignKey)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
}
}
}
CODE LISTING 3
private VehicleContext _vehicleContext;
private IMailService _mailService;
private IConfigurationRoot _config;
public HomeController(IMailService mailService_, IConfigurationRoot
config_, VehicleContext vehicleContext_)
{
_vehicleContext = vehicleContext_;
_mailService = mailService_;
_config = config_;
}
public IActionResult Index()
{
var vehicleData = _vehicleContext.VehicleMakes.ToList();
return View();
}
I think you missing an using statement.
using System.Linq;

System.Data.Entity.ModelConfiguration missing in EF core

Trying to load all the configurations dynamically on OnModelCreating for Entity framework core.
what is the other way around if ModelConfiguration is missing.
It's even easier in Core 2.0 now
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace MyApp.DAL.EntityConfigurations
{
public class StudentConfiguration : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> modelBuilder)
{
modelBuilder.Property(f => f.Name).IsRequired();
}
}
}
Then in your db context:
public DbSet<Student> Students{ get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customizations must go after base.OnModelCreating(builder)
builder.ApplyConfiguration(new StudentConfig());
builder.ApplyConfiguration(new SomeOtherConfig());
// etc.
// etc..
}
I've just stumbled across this question as I was searching for the answer myself. I found that it is not (yet?) implemented in EF Core but can be implemented yourself fairly easily.
You can create one of these:
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Microsoft.EntityFrameworkCore
{
public abstract class EntityTypeConfiguration<TEntity> where TEntity : class
{
public abstract void Map(EntityTypeBuilder<TEntity> modelBuilder);
}
public static class ModelBuilderExtensions
{
public static void AddConfiguration<TEntity>(this ModelBuilder modelBuilder, EntityTypeConfiguration<TEntity> configuration) where TEntity : class
{
configuration.Map(modelBuilder.Entity<TEntity>());
}
}
}
And then you can create a configuration for the entity itself: -
using Microsoft.EntityFrameworkCore;
using Project.Domain.Models;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Project.Persistance.EntityConfigurations
{
public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
public override void Map(EntityTypeBuilder<MyEntity> modelBuilder)
{
modelBuilder
.Property();//config etc
}
}
}
You can then load all your configurations somewhere (there's probably both a better way and a better place for doing it... but this is what I did): -
using Microsoft.EntityFrameworkCore;
using Project.Domain.Models;
using Project.Persistance.EntityConfigurations;
namespace Project.Persistance
{
public class MyDbContext : DbContext
{
// Normal DbContext stuff here
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddConfiguration(new MyEntityConfiguration());
}
}
}

Entity framework add-migration scaffold with custom Migration base

I need to scaffold migration with add-migration from Package Manager Console with my custom Migration base CustomMigration which is derived from DbMigration.
public partial class NewMigration: CustomMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
I can use different command if needed. I don't have any skills in powershell scripting. How can i achieve this?
I Created new class which generated my migrations:
public class AuditMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void WriteClassStart(string #namespace, string className, IndentedTextWriter writer, string #base, bool designer = false, IEnumerable<string> namespaces = null)
{
#base = #base == "DbMigration" ? "AuditMigration" : #base;
var changedNamespaces = namespaces?.ToList() ?? new List<string>();
changedNamespaces.Add("Your.Custom.Namespace");
base.WriteClassStart(#namespace, className, writer, #base, designer, changedNamespaces);
}
}
In Configuration.cs :
internal sealed class Configuration : DbMigrationsConfiguration<EfDataAccess>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = false;
CodeGenerator = new AuditMigrationCodeGenerator();
}
}
And it will use your Custom code generator, which generates migrations with my desired custom migration base.
For more info: https://romiller.com/2012/11/30/code-first-migrations-customizing-scaffolded-code/
run command add-migration NewMigration. It will add new migration with name "NewMigration". If there is no changes in model, the migration will be empty:
public partial class NewMigration : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Change base class of NewMigration to CustomMigration:
public partial class NewMigration : CustomMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
modify NewMigration as you wish
run update-database to apply migration

Code First Migrations without NuGet

I'm wondering how I can use Entity Framework's Code First Migrations without using NuGet at all (so no commands via the package manager console).
I tried the following:
Database-Context
public sealed class MyContext : DbContext
{
private const string ConnectionStringName = "MyDatabase";
public MyContext()
: base(ConnectionStringName)
{}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
SetupMyModel(modelBuilder);
}
}
Migration-Configuration
public class MyMigrationConfiguration : DbMigrationsConfiguration<MyContext>
{
public MyMigrationConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}
Database-Initializer
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MyMigrationConfiguration>());
InitialDatabaseCreation Migration
public class InitialDatabaseCreation : DbMigration, IMigrationMetadata
{
public override void Up()
{
CreateTable("dbo.MyModel",
c => new
{
Id = c.Guid(false, true),
SomeProperty = c.Int(false)
})
.PrimaryKey(x => x.Id);
}
public override void Down()
{
DropTable("dbo.MyModel");
}
public string Id
{
get { return "0001_InitialDatabaseCreation"; }
}
public string Source
{
get { return null; }
}
public string Target
{
get { return Id; }
}
}
As you can see, I wrote a context, a migration configuration and the migration itself.
For the Migration, I'm not sure, if I implemented the IMigrationMetadata correcly. For the Target I just use the id, because I don't want to have any automatic migrations or the ability to use the package manager console. I think, this should be fine here?
I set a breakpoint at the Up method and debugged it, but it does not stop there, which means it doesn't get executed.
Therefor I want to know how to use the EF Code First migrations when writing everything manually.