User Tools

Site Tools


Sidebar

Nebol Software Projects:

.NET Class Libraries

Contact info:

johan@nebol.se

nebolcontroller_netcore_mssql_adjustments

WORK IN PROGRESS

DAL project:

Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.SqlServer # if needed for any MSSQL stuff in your DbContext

Add Models

Add a DbContext

public class MyDbContext : DbContext
{
	public MyDbContext()
	{
	}

	public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
	{
	}

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		optionsBuilder.UseSqlServer(Config.ConnectionString);
	}

	public static MyDbContext Create()
	{
		var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
		optionsBuilder.UseSqlServer(Config.ConnectionString);
		return (new MyDbContext(optionsBuilder.Options));
	}

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		modelBuilder.RemovePluralizingTableNameConvention();

		base.OnModelCreating(modelBuilder);
	}

	public DbSet<Parent> Parents { get; set; }
	public DbSet<Child> Children { get; set; }
}

Here's a RemovePluralizingTableNameConvention() that works for .NET Core:

public static class ModelBuilderExtensions
{
	public static void RemovePluralizingTableNameConvention(this ModelBuilder modelBuilder)
	{
		foreach (IMutableEntityType entity in modelBuilder.Model.GetEntityTypes())
		{
#if (NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2)
			entity.Relational().TableName = entity.DisplayName();
#else // for 3.0 and onwards
			entity.SetTableName(entity.DisplayName());
#endif
		}
	}
}

Update Entity Framework Tools if needed

PM> dotnet tool update –global dotnet-ef

Create a migration

dotnet ef migrations add InitialCreate --project MyProject.DAL

Update the database

dotnet ef database update --project Mixer.DAL

Main project:

Add ViewModels Add Profiles Add Specifications

nebolcontroller_netcore_mssql_adjustments.txt · Last modified: 2021/08/02 03:07 by nebol