IT College 2016, Andres käver

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

Bruce Scharlau, University of Aberdeen, 2012 Data storage options for mobiles Mobile Computing.
Entity Framework Code First Migrations

.NET Database Technologies: Open-Source Frameworks.
Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Telerik School Academy.
Introduction to Entity Framework Part 1 Tom Perkins NTPCUG.
Part 05 – Code First Migrations and Azure Deployment Entity Framework and MVC Series Tom Perkins NTPCUG.
ORM Technologies and Entity Framework (EF)
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Neo.NET Entity Objects Design Goals Copyright © Erik Dörnenburg – Last updated: May 2004.
Introduction to MVC Adding Model Classes NTPCUG Tom Perkins, Ph.D.
Entity Framework Code First End to End
.NET Database Technologies: Entity Framework additional notes – part 2.
Connecting a.NET application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.
Introduction to ASP.NET MVC Information for this presentation was taken from Pluralsight Building Applications with ASP.NET MVC 4.
OVERVIEW ON HOW ENTITY FRAMEWORK CODE FIRST CAN EASE THE DEVELOPMENT PROCESS Entity Framework Code First 11/19/2013 Joe Walling Copyright Walling Info.
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
Entity Framework Code First – Beyond the Basics Sergey Barskiy, Magenic Microsoft MVP – Data Platform Principal Consultant.
Entity Framework: Code First SoftUni Team Technical Trainers Software University
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
All information's of PLINQO in this Document, I got it from: So, you could visit the link above to research.
Entity Framework Code First – Beyond the Basics Sergey Barskiy, Magenic Microsoft MVP – Data Platform Magenic, Principal Consultant Level: Introductory.
Entity Framework 7 Who Are You & What Have You Done to my ORM?
Entity Framework Code First
Simplifying the Code First Approach in the Entity Framework Dhananjay Kumar Infragistics Consultant Microsoft MVP
Stuart Leitch “Code First” & DbContext.
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
Рис.1. Схема взаємодії компонентів ASP.NET MVC Контролер (controller) - клас, з якого починається робота програми. Забезпечує зв'язок між моделлю і представленням.
BIT 286: Web Applications ASP.Net MVC. Objectives Applied MVC overview Controllers Intro to Routing Views ‘Convention over configuration’ Layout files.
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
ASP.NET Core* Shahed Chowdhuri Sr. Technical WakeUpAndCode.com A Quick Overview of ASP.NET Core * aka ASP.NET 5 before.
Andres Käver, IT Kolledž public interface IPersonRepository : IDisposable { IQueryable All { get; } IQueryable AllIncluding( params Expression.
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
Entity Framework (EF) ORM and Entity Framework Code First. CRUD Operations SoftUni Team Technical Trainers Software University
Build Data Driven Apps with ASP.NET Core Rachel Appel.
Top 10 Entity Framework Features Every Developer Should Know
Working with Fluent API Inheritance Strategies
Introduction to Entity framework
Building Web Applications with Microsoft ASP
Introduction to .NET Florin Olariu
Introduction to Entity Framework
EF Code First (Advanced)
EF Advanced Querying Optimize Performance SoftUni Team Advanced
EF Relations Object Composition
Building Web Applications with Microsoft ASP
Entity Framework: Code First
Entity Framework DB From Code, OOP Introduction
A very brief introduction
Entity Framework By: Casey Griffin.
PHP Training at GoLogica in Bangalore
Entity Framework Core for Enterprise Applications
Learn. Imagine. Build. .NET Conf
SharePoint Cloud hosted Apps
Buổi 7 Mô hình CSDL Entity Framework code first
Repository pattern Andres Käver, IT Kolledž 2016/2017 Spring.
Entity Framework Code-First Migrations
Entity Framework Core for Enterprise Applications
C# - EF Core IT College, Andres Käver, , Fall semester
…and web frameworks in general
Implementing Entity Framework with MVC Jump Start
C# - EF Core Intro IT College, Andres Käver, , Fall semester
C# - Razor Pages Db/Scaffolding/Async
02 | Beginning Code First Adam Tuliper | Technical Evangelist
Entity Framework & LINQ (Language Integrated Query)
Presentation transcript:

IT College 2016, Andres käver http://enos.itcollege.ee/~akaver/csharp C# - Entity Framework IT College 2016, Andres käver http://enos.itcollege.ee/~akaver/csharp

C# - ORM ORM – Object Relational Mapping .NET ORM systems For converting data between incompatible type systems in oop languages. In effect creates “virtual object database”, for using within the oop language .NET ORM systems Entity Framework – Microsoft NHibernate Dapper … and many others

C# - EF Model, databse or code first?

C# - EF, Code First Code First approach Write your business classes Add relationships between classes Add attributes Add custom getters and setters where needed EF will construct database based on your classes EF will handle all the CRUD, converting code into sql clauses

C# - EF conventions Every entity (class) has to contain attribute suitable for primary key (PK) Attribute with name Id or <EntityName>Id is automatically taken as PK Other conventions set string length, structure of tables in case of inheritance, cascade delete, etc Every convention in EF can be configured or changed You can add your own conventions

C# - EF and DbContext Entities have no idea of EF To use EF you need to add class, that inherits from DbContext Inside DbContext, add neccesary DbSet<Entity> attributes Relational tables are created automatically DbContext – database, DbSet – table in database

C# - EF, DbContext public class ContactContext : DbContext { public DbSet<Person> People { get; set; } public DbSet<Contact> Contacts { get; set; } public DbSet<ContactType> ContactTypes { get; set; } }

C# - EF, DB initialization EF will create your DB on first access Afterwards, when you change your domain classes – exception: EF will create in memory model of your Db structure and save its hash into db. During next db initialization hashes are compared – if they are not matching – db is changed from outside. Solution – migrations (data is retained) or recreation (data is lost) of db. The model backing the 'ContactContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

C# - EF, Db initialization Different strategies exist CreateDatabaseIfNotExists – default DropCreateDatabaseIfModelChanges DropCreateDatabaseAlways MigrateDatabaseToLatestVersion Or create your own Set DB initializer in your DbContext class constructor Database.SetInitializer<MyDBContext>(new DropCreateDatabaseIfModelChanges <MyDBContext>());

C# - EF, annotations, Fluent API Annotations are the simplest way to configure your entities for EF Several frameworks use the same annotations (MVC, Web Api, EF) Annotations don’t cover all options Fluent API is capable of full EF configuration. But only EF sees those configurations. It is necessary to use both options. using System.ComponentModel.DataAnnotations; ... public class ContactType { ... [Required] [MaxLength(128)] public String Name { get; set; } ... } ... public class ContactConfiguration : EntityTypeConfiguration<Contact> { public ContactConfiguration() Property(t =>t.Value).IsRequired().HasMaxLength(128); }

C# - EF, Key [Key] Sets, that this attribute is used as primary key in Db Fluent: Entity<T>.HasKey(t=>t.PropertyName)

C# - EF, Required [Required] Attribute value is required, NULL is not allowed in Db Fluent: Entity<T>.Property(t=>t.PropertyName). IsRequired

C# - EF, MaxLength, MinLength [MaxLength(xxx)] Max length of string, db type is nvarchar(xxx) [MinLength(yyy)] String minimum length, used in client side validation (MVC), no Fluent API. Fluent: Entity<T>.Property(t=>t.PropertyName). HasMaxLength(nn)

C# - EF, NotMapped [NotMapped] If attribute is synthetic (calculated) and not stored into Db Fluent: Entity.Ignore(d => d.Property);

C# - EF, ForeignKey [ForeignKey("XxxId")] – on object [ForeignKey("XxxName")] – on Id Used in case of multiple same type relationships, or if names and keynames of entities don’t match Fluent: modelBuilder.Entity<>().HasRequired().WithMany(). HasForeignKey();

C# - EF, Fluent API using System.Data.Entity; using System.Data.Entity.ModelConfiguration; namespace ContactsLibrary { public class PersonConfiguration : EntityTypeConfiguration<Person>{ public PersonConfiguration() Property(l => l.FirstName).IsRequired().HasMaxLength(150); } public class ContactContext : DbContext{ public DbSet<Person> People { get; set; } public DbSet<Contact> Contacts { get; set; } public DbSet<ContactType> ContactTypes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) modelBuilder.Configurations.Add(new PersonConfiguration());

C# - Fluent API only configurations Decimal precision (default 18,2) Entity<T>.Property(t=>t.PropertyName). HasPrecision(n,n) Defining relationships Entity.Has[Multiplicity](Property). With[Multiplicity](Property) Has – HasOptional, HasRequired, HasMany With – WithOptional, WithRequired, WithMany Disabling cascade delete Entity.HasRequired().WithMany(). WillCascadeOnDelete(false) Changing conventions: modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); http://msdn.microsoft.com/en-us/library/gg696316

C# - EF Logging To see, what EF is doing context.Database.Log = Console.Write; Context.Database.Log is an Action<string> so that you can attach any method which has one string parameter and void return type. public class Logger { public static void Log(string message) Console.WriteLine("EF Message: {0} ", message); }

C# - EF, Db connection EF system configuration is in startup project config file (app.config) Add connection string Use it in DbContext constructor <configuration> <configSections> </configSections> <connectionStrings> <add name="DataBaseConnectionStr" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=mydbname;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" /> </connectionStrings> public class MyDBContext: DbContext { public MyDBContext(): base(“name=DataBaseConnectionStr")

The end is near….

The end