450 likes | 570 Views
ASP.NET MVC Working with Data. Nikolay K ostov. Telerik Software Academy. Senior Software Developer and Trainer. http://nikolay.it. Table of Contents. ADO.NET Entity Framework and LINQ Code-first approach Scaffolding Model Binders Data Validation Kendo UI Grids.
E N D
ASP.NET MVCWorking with Data Nikolay Kostov Telerik Software Academy Senior Software Developer and Trainer http://nikolay.it
Table of Contents • ADO.NET Entity Framework and LINQ • Code-first approach • Scaffolding • Model Binders • Data Validation • Kendo UI Grids
ADO.NET Entity Framework Object Relation Persistence Framework
Overview of ADO.NET EF • Entity Framework (EF) is a standard ORM framework, part of .NET • Provides a run-time infrastructure for managing SQL-based database data as .NET objects • The relational database schema is mapped to an object model (classes and associations) • Visual Studio has built-in tools for generating Entity Framework SQL data mappings • Data mappings consist of C# classes and XML • A standard data manipulation API is provided
Entity Framework Features • Entity Framework (EF) standard features: • Maps tables, views, stored procedures and functions as .NET objects • Provides LINQ-based data queries • Executed as SQLSELECTs on the database server • CRUD operations – Create/Read/Update/Delete • Create compiled queries – for executing the same parameterized query multiple times • Creating or deleting the database schema
Entity Framework Lifecycle • When the application starts • EF translates into SQL the language-integrated queries in the object model • Sends them to the database for later execution
Entity Framework Lifecycle (2) • When the database returns the results • Entity Framework translates the database rows back to .NET objects • The database server is transparent, hidden behind the API • LINQ is executed over IQueryable<T> • At compile time a query expression tree is emitted • At runtime SQL is generated and executed
EF Components • The ObjectContextclass • ObjectContextholds the database connection and the entity classes • Provides LINQ-based data access • Implements identity tracking, change tracking, and API for CRUD operations • Entity classes • Each database table is typically mapped to a single entity class (C# class)
EF Components (2) • Associations • An association is a primary key / foreign key based relationship between two entity classes • Allows navigation from one entity to another, e.g. Student.Courses • Concurrency control • EntityFramework uses optimistic concurrency control (no locking by default) • Provides automatic concurrency conflict detection and means for conflicts resolution
LINQ • Comprehension Query Syntax • Extension Method Syntax
Entity Framework SQL Server (compact) Schema First (database) MySQL Entity Framework (+ LINQ) Model First (model designer) Azure (cloud) Code First (C# classes) Oracle
What isMicrosoft SQL Server? • MS SQL Server is a Relational Database Management System(RDBMS) from Microsoft • The main language supported in SQL Server isTransact SQL (T-SQL), an extension of SQL • Powerful, trustworthy, easy-to-use DB server • The most recent version isSQL Server 2012 • Works only on Windows systems • A free distribution exists (SQL Server Express) • http://www.microsoft.com/express/database/
Entity Framework Models Design First Code First Model First Create .edmx model in designer Generate DB from .edmx Classes auto-generate from .edmx Code First Define classes & mapping in code Database auto-created at runtime New Database Code First Define classes & mapping in code Database First Reverse engineer .edmx model Classes auto-generate from .edmx Existing Database
Code First Approach • Convention over configuration • Database naming • Primary Key • Relationships (navigation properties) • Data Annotations • Tells EF how to map the object model to the database model • Place annotations directly against the property in your class • System.ComponentModel.DataAnnotations
Common Data Annotations • Key – Defines a Primary Key • Column – Defines DB column name • Table – Defines table name for a class • Required – Defines a Required DB field • NotMapped – Property not in DB mapping • MinLength() – Min length for a property • MaximumLength() – Max length for property • Range() – Defines a valid value range
Database Migrations • Package Manager Console • Enable-Migrations (-ContextTypeName) • This creates a Migration folder in project • Creates Configuration.csfile • AutomaticMigrationsEnabled = true; • Seed method to populate some initial data • Creates __MigrationHistory system table in DB • Update-Database (-Verbose) • Pushes the migration changes to the DB • –script – create a SQL script of the changes
Custom Mapping • When the database doesn’t match conventions …
Demo: Create Entities and Context Please work, please work, please work…
Controller and View Templates • TODO: Editor templates and view templates
Model Binders • To make east of handling HTTP post request • Help the populating the parameters in action methods DefaultModelBinder HTTP POST /Review/Create Rating=7&Body=Great!
Validation with Annotations • Attributes defined in System.ComponentModel.DataAnnotations • Covers common validation patterns • Required • StringLength • Regex • Range
Custom Validation • Custom attributes • Inherit ValidationAttribute
Validating Model – Controller • ModelState.IsValid – will give us information about the data validation success • ModelState.AddModelError – custom error
Validating Model – View • @Html.ValidationSummary– output errors • @Html.ValidationMessageFor(…) – outputs validation message for specified property Text box with integrated client-side validation jQuery validation library required for unobtrusive JavaScript validation
Summary • TODO: Summary
ASP.NET MVCWorking with Data http://schoolacademy.telerik.com
Free Trainings @ Telerik Academy • “C# Programming @ Telerik Academy • csharpfundamentals.telerik.com • Telerik Software Academy • academy.telerik.com • Telerik Academy @ Facebook • facebook.com/TelerikAcademy • Telerik Software Academy Forums • forums.academy.telerik.com