Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# - EF Core IT College, Andres Käver, , Fall semester

Similar presentations


Presentation on theme: "C# - EF Core IT College, Andres Käver, , Fall semester"— Presentation transcript:

1 C# - EF Core IT College, Andres Käver, 2018-2019, Fall semester
Web: Skype: akaver

2 EF Core Add simple logging, to see generated SQL statements on console
Define LoggerFactory public class AppDbContext : DbContext { public static readonly LoggerFactory MyLoggerFactory = new LoggerFactory(new[] { new ConsoleLoggerProvider((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information, true) });

3 EF Core Use logger on optionsBuilder
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder .UseLoggerFactory(MyLoggerFactory) .UseSqlServer( @"Server=(localdb)\mssqllocaldb;" + // server to use "Database=MyDatabase;" + // database to use or create "Trusted_Connection=True;" + // no credentials needed, local sql instance "MultipleActiveResultSets=true" // allow multiple parallel queries ); }

4 EF Core - Migrations Package manager console Console command line
Add-Migration InitialDbCreation Update-Database Console command line dotnet ef migrations add InitialDbCreation dotnet ef database update From code myDbContext.Database.Migrate();

5 EF Core – Data access Eager, Explicit, Lazy
Eager – load all data at once Explicit – load data, when needed Lazy – load data automatically when accessing navigation property, without doing specific db operations Lazy - not recommended. 1+N query problem.

6 EF Core – Data access Eager – specify data to include in query results (JOIN) .Include(table => table.ListOfRelatedEntity) Eager – include several relationships .Include(table => table.ListOfRelatedEntity) .Include(table => table.ListOfSomeOtherRelatedEntity) Eager – include multiple levels .Include(table => table.ListOfRelatedEntityA) ThenInclude(RelatedEntityA => table.ListOfSomeOtherRelatedEntityBFromEntityA)

7 EF Core - PK Use conventions! <ClassName>Id or just Id
Annotations [Key] Fluent API modelBuilder.Entity<ModelClass>() .HasKey(c => c.KeyProperty); Composite key – only in Fluent API modelBuilder.Entity<ModelClass>() .HasKey( c => new { c.KeyProperty1, c.KeyProperty2 });

8 EF Core - Generated properties
Value generation No value Value generated on add Value generated on add or update Annotations [DatabaseGenerated(DatabaseGeneratedOption.None)] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [DatabaseGenerated(DatabaseGeneratedOption.Computed)] Fluent API modelBuilder.Entity<ModelClass>().Property( b => KeyProperty.ValueGeneratedNever(); modelBuilder.Entity<ModelClass>().Property( b => b.InsertedProperty).ValueGeneratedOnAdd(); modelBuilder.Entity<ModelClass>().Property( b => b. LastUpdatedProperty).ValueGeneratedOnAddOrUpdate();

9 EF Core - Required/Optional
If property is nullable – by convention not required Annotations [Required] Fluent API modelBuilder.Entity<ModelClass>() .Property( b => b.SomeProperty).IsRequired();

10 EF Core – Maximum Length
By convention depends on the provider Annotation [MaxLength(<Length>)] Fluent API modelBuilder.Entity<ModelClass>().Property( b => b.SomeProperty) .HasMaxLength(<Length>);

11 EF Core - Indexes Index is created for every foreign key
Annotations – not possible Fluent API Single property, non-unique modelBuilder.Entity<ModelClass>() .HasIndex(b => b.SomeProperty); Unique modelBuilder.Entity<ModelClass>() .HasIndex( b => b. SomeProperty) .IsUnique(); More than one property modelBuilder.Entity<ModelClass>() .HasIndex( p => new { p. SomeProperty1, p. SomeProperty2 });

12 EF Core - Table/Column maping
Annotations [Table(“TableName”)] [Column(“ColumnName”)] Fluent API modelBuilder.Entity<ModelClass>() .ToTable(”TableName"); modelBuilder.Entity<ModelClass>() .Property( b => b.SomeProperty) .HasColumnName(”ColumnName");

13 EF Core – Default value Fluent API only modelBuilder.Entity<ModelClass>().Property( b => b.SomeNumber) .HasDefaultValue(3); modelBuilder.Entity<ModelClass>().Property( b => b.SqlProperty) .HasDefaultValueSql("getdate()");

14 EF Core – Exclude properties
You can exclude types or properties from DB Annotations [NotMapped] Fluent API (in dbcontext.OnModelCreating) modelBuilder.Ignore<ModelClass>(); modelBuilder.Entity<ModelCalss>() .Ignore(b => b.ModelProperty); Getter only properties are excluded automatically

15 EF Core - Relationships
If possible, use fully defined relationships Navigation property defined on both ends, FK defined in dependent entity If there is only one relationship between two entities, EF will set up relationship automatically Some configuration is needed on other cases Data annotations [ForeignKey] [InverseProperty]

16 EF Core - Relationships
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogForeignKey { get; set; } [ForeignKey("BlogForeignKey")] public Blog Blog { get; set; } [ForeignKey] – when FK is not discovered [ForeignKey( nameof(Post.BlogForeignKey))]

17 EF Core - Relationships
public class Post{ public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int AuthorUserId { get; set; } public User Author { get; set; } public int ContributorUserId { get; set; } public User Contributor { get; set; } } [InverseProperty] Used, when there are more than one relationships defined between two entities public class User{ public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [InverseProperty("Author")] public List<Post> AuthoredPosts { get; set; } [InverseProperty("Contributor")] public List<Post> ContributedToPosts { get; set; } }

18 EF Core - Relationshps Fluent API
To configure a relationship in the Fluent API, you start by identifying the navigation properties that make up the relationship. HasOne or HasMany identifies the navigation property on the entity type you are beginning the configuration on. You then chain a call to WithOne or WithMany to identify the inverse navigation. protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Post>() .HasOne(p => p.Blog) .WithMany(b => b.Posts); }

19 EF Core – Cascade delete
Cascade delete is automatically configured The default EF Core 2.0 convention is to use DeleteBehavior.Cascade for required and DeleteBehavior.ClientSetNull for optional relationships. You can turn of cascade delete for all entities (in DbContext): protected override void OnModelCreating(ModelBuilder modelBuilder){ foreach (var relationship in modelBuilder.Model .GetEntityTypes() .Where(e => !e.IsOwned()) .SelectMany(e => e.GetForeignKeys())) { relationship.DeleteBehavior = DeleteBehavior.Restrict; } base.OnModelCreating(modelBuilder);

20 EF Core – Preexisting db
PM Console > Scaffold-DbContext -Connection <String> The connection string to the database. Required. -Provider <String> The provider to use. Typically this is the name of the NuGet package, for example: Microsoft.EntityFrameworkCore.SqlServer. This is a positional parameter and is required. -OutputDir <String> The directory to put files in. Paths are relative to the project directory. -ContextDir <String> The directory to put the DbContext file in. Paths are relative to the project directory. -Context <String> The name of the DbContext class to generate. -DataAnnotations Use attributes to configure the model (where possible). If this parameter is omitted, only the fluent API is used. -Force Overwrite existing files. Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

21 EF Core – Preexisting db
Command prompt >dotnet ef dbcontext scaffold "server=alpha.akaver.com;database=databasename;user=user;pas sword=pass" MySql.Data.EntityFrameworkCore --data-annotations --context AppDbContext --output-dir Models --context-dir / --project DAL --startup-project ConsoleApp1


Download ppt "C# - EF Core IT College, Andres Käver, , Fall semester"

Similar presentations


Ads by Google