10.3 Definig EF Core models -> Adding tables to the Northwind database context class
This commit is contained in:
parent
4e99e8c92b
commit
b851fd937a
@ -1,9 +1,14 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using static System.Console;
|
||||
|
||||
namespace Packt.Shared;
|
||||
|
||||
public class Northwind : DbContext
|
||||
{
|
||||
// These properties map to tables in database
|
||||
public DbSet<Category>? Categories { get; set; }
|
||||
public DbSet<Product>? Products { get; set; }
|
||||
|
||||
protected override void OnConfiguring(
|
||||
DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
@ -17,10 +22,28 @@ public class Northwind : DbContext
|
||||
else
|
||||
{
|
||||
string connection = "Data Source=.;" +
|
||||
"Initial Catalog=Northwind;" +
|
||||
"Integrated Security=true;" +
|
||||
"MultipleActiveResultSets=true;";
|
||||
"Initial Catalog=Northwind;" +
|
||||
"Integrated Security=true;" +
|
||||
"MultipleActiveResultSets=true;";
|
||||
optionsBuilder.UseSqlServer(connection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnModelCreating(
|
||||
ModelBuilder modelBuilder)
|
||||
{
|
||||
// example of using Fluent API instead of attributes
|
||||
// // to limit the length of a category name to 15
|
||||
modelBuilder.Entity<Category>()
|
||||
.Property(category => category.CategoryName)
|
||||
.IsRequired() // NOT NULL
|
||||
.HasMaxLength(15);
|
||||
if (ProjectConstants.DatabaseProvider == "SQLite")
|
||||
{
|
||||
// added to "fix" the lack of decimal support in SQLite
|
||||
modelBuilder.Entity<Product>()
|
||||
.Property(product => product.Cost)
|
||||
.HasConversion<double>();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user