Tuesday, January 24, 2017

Adding / Modifying Database objects to EDMX

Entity Framework has the ability to automatically build native commands for the database based on your LINQ to Entities or Entity SQL queries, as well as build the commands for inserting, updating, or deleting data. You may want to override these steps and use your own predefined database objects instead.

Entity Framework lets you override it's built in functionality and use your own predefined database objects. Here in this illustration I am trying to walk you through the way of working with Stored Procedures and Table Valued Functions.

Stored Procedures in Entity Framework:

Database objects like Stored procedures and user-defined functions (UDFs) are represented as functions in Entity Framework. So these will not have any defined entity representation in the EDM designer.

For this example walk through of how to work with Stored Procedures in EF, we will consider overriding EF's Find All Courses for a Student functionality with an existing Stored Procedure called "GetCoursesByStudentId" as below:

  • Create new ADO.NET Entity Model (.edmx) by picking "EF Designer from Database" option from Choose Model Contents section, and click "Next"
  • On Choose your Database Objects and Settings section, select "GetCoursesByStudentId" stored procedure by navigating to the object as below. Don't forget to check option "Import selected stored procedures and functions into the entity model", and clicck "Finish"
  • You will see GetCoursesByStudentId added in Function Imports with new complex type GetCoursesByStudentId_Result in the Model Browser. Whenever you import a stored procedure into a model, it creates new complex type with the name {sp name}_Result by default.
  • No need to add a new compex type for the returned data from GetCoursesByStudentId as it returns the same fields defined in Course entity. You can change it by right clicking on GetCoursesByStudentId in function imports and selecting Edit. Check Entities and select Course from dropdown in popup window as shown below:
  • You will see the function in the context class for GetCoursesByStudentId as shown below:
  • Now, GetCoursesByStudentId function can be called as below to get the result, which is equivalent to
    exec [dbo].[GetCoursesByStudentId] @StudentId=1
  • using (var context = new SchoolDBEntities())
    {
    var courses = context.GetCoursesByStudentId(1);

    foreach (Course cs in courses)
    Console.WriteLine(cs.CourseName);
    }
Table-Valued Functions in Entity Framework

Table-valued functions are similar to stored procedure with one key difference: the result of TVF is composable which means results of TVF can be used in a LINQ query.

  • Here is how we can include a Table-Valued function to our EDM. Right click on the designer → select Update Model from the Database.
  • Expand Stored Procedures and Functions node → expand schema node (dbo schema in our case) → select 'GetCourseListByStudentID' and click Finish. Make sure that checkbox for 'Import selected procedures and functions into the entity model' is checked (this will import the function automatically).
  • After you imported the function, you can verify it: Open Model Browser → expand Function Imports → right click on imported function 'GetCourseListByStudentID' → click Edit:
  • You can see that EDM has automatically created the complex type GetCourseListByStudentID_Result as a return collection type.
  • You can also select an existing entity as a return type if TVF returns the same columns as entity:
  • Now, the created Table-Valued function can be used in code as beow:
  • using (var ctx = new SchoolDBEntities())
    {
    //Execute TVF and filter result
    var courseList = ctx.GetCourseListByStudentID(1).Where(c => c.Location == "City1")
    .ToList();

    foreach (GetCourseListByStudentID_Result cs in courseList)
    Console.WriteLine("Course Name: {0}, Course Location: {1}", cs.CourseName, cs.Location);
    }
Modifying / Refreshing Database Objects

Following below steps, we can apply the changes made to the existing database objects:
  • Make sure that the connection string used in .edmx is activate by saving config file (even though no changes made to it)
  • Open .edmx file and select "Model Browser" option by right clicking on .edmx file, and pick "Update Model from Database" option by right clicking on "Stored Procedures / Functions" option from Model Browser window
  • Pick "Refresh" tab from "Update Wizard" window. Select database object by expanding "Stored Procedure and Functions" node to refresh and click "Finish", as below:

With this I am concluding the illustration. Feel free to share your feedback.

Happy Programming !!!

Friday, January 20, 2017

EF Architecture and Fundamentals

ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework which:
  • Enable developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write, OR simply Is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database, and for working with the results in addition to DataReader and DataSet
  • Provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals
  • Is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way without much programming
  • Allows us to keep our database design separate from our domain class design. This makes the application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so that the developer doesn't need to write it manually
  • Includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects map to relational database objects (tables, views & stored procedures)

Architecture

EDM (Entity Data Model):consists of below three parts:
  • Conceptual Model: The conceptual model contains the model classes and their relationships. This will be independent from your database table design
  • Storage Model: Storage model is the database design model which includes tables, views, stored procedures and their relationships and keys
  • Mapping: Mapping consist information about how the conceptual model is mapped to storage model

LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL: Entity SQL is another query language just like LINQ to Entities. However, it is a little more difficult than L2E and also the developer will need to learn it separately.

Object Service: Object service is a main entry point for accessing data from the database and to return it back. Object service is responsible for materialization, which is process of converting data returned from entity client data provider (next layer) to an entity object structure.

Entity Client Data Provider: The main responsibility of this layer is to convert L2E or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from database.

ADO.Net Data Provider: This layer communicates with database using standard ADO.Net.


Types of Entities: There were four types of Entities in Entity Framework 4.x, but from 5.0 is limited to POCO and POCO Proxy entities.
  • EntityObject
  • POCO (Plain Old CLR Object): It is like any other normal .net class. These support most of the same query, insert, update, and delete behaviors as entity types that are generated by the Entity Data Model
  • POCO Proxy (dynamic proxy): Dynamic Proxy is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity if it meets certain requirements in order to enable lazy loading and automatic change tracking. It adds some methods at runtime to your POCO class which does instant change tracking and lazy loading stuff
  • Self-Tracking Entities

POCO entity should meet the following requirements to become a POCO proxy:
  • A custom data class must be declared with public access.
  • A custom data class must not be sealed (NotInheritable in Visual Basic)
  • A custom data class must not be abstract (MustInherit in Visual Basic).
  • ProxyCreationEnabled option should not set to false (default is true) in context class
  • Each navigation property must be declared as public, virtual

By default dynamic proxy is enabled for every entity. However, you can disable dynamic proxy by setting the ProxyCreationEnabled option to false in context class. context.Configuration.ProxyCreationEnabled = false;

EDM generates POCO entities which satisfy the above requirements for a dynamic proxy by default. You can use ObjectContext.GetObjectType() to find the actual type of dynamic proxy.


Entity Properties
  • Scalar properties: Scalar properties are properties whose actual values are contained in the entity. For example, Student entity has scalar properties e.g. StudentId, StudentName. These correspond with the Student table columns.
  • Navigation properties: Navigation properties are pointers to other related entities. The Student has Standard property as a navigation property that will enable application to navigate from a Student to related Standard entity.

Querying with EDM

You can query EDM mainly in three ways: LINQ to Entities, Entity SQL, and Native SQL

LINQ to Entities: L2E query syntax is easier to learn than Entity SQL. You can use your LINQ skills for querying with EDM. These are LINQ Method Syntax with Lamda expression OR by LINQ query syntax itself, examples as below:

LINQ Method Syntax:
using (var context = new SchoolDBEntities())
{
var L2EQuery = context.Students.where(s => s.StudentName == “Bill”);
}
LINQ Query Syntax:
using (var context = new SchoolDBEntities())
{
var L2EQuery = (from st in context.Students
where st.StudentName == "Bill"
select st);
}
Entity SQL: Entity SQL is another way to create a query. It is processed by the Entity Framework’s Object Services directly. It returns ObjectQuery instead of IQueryable. You need ObjectContext to create a query using Entity SQL. The following code snippet shows the same query result as L2E query above:
string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students AS st WHERE st.StudentName == 'Bill'";

var objctx = (ctx as IObjectContextAdapter).ObjectContext;

ObjectQuery student = objctx.CreateQuery(sqlString);
Student newStudent = student.First();

You can also use EntityConnection and EntityCommand to execute Entity SQL as shown below:

using (var con = new EntityConnection("name=SchoolDBEntities"))
{
con.Open();
EntityCommand cmd = con.CreateCommand();

cmd.CommandText = "SELECT VALUE st FROM SchoolDBEntities.Students as st where st.StudentName='Bill'";
Dictionary dict = new Dictionary();

using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
int a = rdr.GetInt32(0);
var b = rdr.GetString(1);
dict.Add(a, b);
}
}
}
Native SQL: You can execute native SQL queries for a relational database as shown below:
using (var ctx = new SchoolDBEntities())
{
var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student
               where studentname='Bill'").FirstOrDefault();
}
With this I am concluding this article. Feel free to share your feedback.

Happy Programming !!!

Monday, January 16, 2017

RequiredIf RegEx - Conditional Validation Attribute using MVC / Web API

This topic illustrates how to extend ValidationAttribute to enforce customized validation of checking if a provided field's value is matching to a pattern (regular expression) or not when dependent field's value is matching to a specific value condition.

Scenario: Address.Phone should accept only numbers between 0-9 when Address.Country's value is "USA".

We can achieve this by following below steps, and the illustration is developed using MVC 5, Web API 2, EF 6 and Mock

As a first step, Create a new class with name "RequiredIfRegExValidator" (preferably in a common location of the solution ie. either in Model or a Common project, as applied) and copy below code:
public class RequiredIfRegExValidator : ValidationAttribute
{
private RequiredAttribute _innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }

public RequiredIfRegExValidator(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.DependentProperty);

if (field != null)
{
var phoneNumber = Convert.ToString(value, CultureInfo.CurrentCulture);

// get the value of the dependent property
object dependentValue = field.GetValue(validationContext.ObjectInstance, null);

// trim spaces and convert dependent value to uppercase to support case senstive comparison
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
dependentValue as string).Length == 0 ? null : (dependentValue as string).ToUpper();
}

// trim spaces and convert TargetValue to uppercase to support case senstive comparison
if (TargetValue != null && TargetValue is string)
{
TargetValue = (TargetValue as string).Trim();
TargetValue = (TargetValue as string).Length == 0 ? null : (TargetValue as string).ToUpper();
}

// compare the value against the target value
if ((dependentValue == null && TargetValue.Equals("") ||
(dependentValue == null && !TargetValue.Equals("") ||
(dependentValue != null && dependentValue.Equals(this.TargetValue)))))
{
// try validating this field
if (!_innerAttribute.IsValid(value))
{
     var match = _regex.Match(phoneNumber);
     if (!match.Success)
           // validation failed - return an error
           return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
}
// validation success - return success
return ValidatioResult.Success;
}
}
We need to create or make changes to Model(s) and Controller(s) as below to implement the created custom validation.

POCO / Model: Create or Modify Address class to apply the custom validation on City property as below to define City is required when selected Country is USA.
public class Address {
public int AddressId {get; set; }

public string Line1 { get; set; }

public string Line2 { get; set; }

public string City { get; set; }

public string State { get; set; }

public string Zip { get; set; }

public IEnumerable Country { get; set; }

[RequiredIfRegExValidator(@"^\d{10}$", "Country", "USA", ErrorMessage = "Phone Requires Numbers between 0-9")]
public string Phone { get; set; }
}
Controller: The controller for Address entity with a POST method will look like below.

Here, before persisting the changes in database, I am forcing process to re-validate Modal State by calling "this.Validate()", which will help the process to identify and throw an error upfront instead of making a call to DB.
public class AddressController : ApiController
{
[ResponseType(typeof(Address))]
public IHttpActionResult PostAddress(Address address)
{
// use below to force validation before doing anything
this.Validate(address);

if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Address.Add(address);
db.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = address.AddressId }, address);
}
}
Testing: Below TestMethods will help testing the post method to check for the expected validation error:

Here, The first test method will represent a case forcing this.Validate() method and second without forcing this.Validate() in controller's POST method.
// Forcing this.Validate() - this case Controller will thow the error
[TestMethod]
public void RequiredPhoneinNumbersWhenCountryIsUSATest()
{
Address address = new Address { Line1 = "200 E Main St", Line2 = "Apt B", State = "VA", Country = "USA", Phone="732654ABC" };
AddressController addressController = new AddressController();
AddressController.Request = new HttpRequestMessage();
AddressController.Request.Properties["MS_HttpConfiguration"] = new HttpConfiguration();

addressController.PostAddress(address);

Assert.IsFalse(addressController.ModelState.IsValid);
Assert.IsTrue(addressController.ModelState.Count == 1, "Phone Requires Numbers between 0-9");
}
// Without forcing this.Validate() - this case DB will throw the error
[TestMethod]
public void RequiredPhoneinNumbersWhenCountryIsUSATest()
{
Address address = new Address { Line1 = "200 E Main St", Line2 = "Apt B", State = "VA", Country = "USA", Phone="732654ABC" };
try
{
AddressController addressController = new AddressController();
AddressController.Request = new HttpRequestMessage();
AddressController.Request.Properties["MS_HttpConfiguration"] = new HttpConfiguration();

addressController.PostAddress(address);
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Assert.AreEqual("Phone Requires Numbers between 0-9", validationError.ErrorMessage);
}
}
}
}
With this I am concluding the illustration. Feel free to share your feedback.

Happy Programming !!!

RequiredIf Not RegEx - Conditional Validation Attribute using MVC / Web API

This topic illustrates how to extend ValidationAttribute to enforce customized validation of checking if a provided field's value is matching to a pattern (regular expression) or not when dependent field's value is not matching to a specific value condition.

Scenario: Address.Phone should accept only numbers between 0-9 when Address.Country's value is not "USA".

We can achieve this by following below steps, and the illustration is developed using MVC 5, Web API 2, EF 6 and Mock

As a first step, Create a new class with name "RequiredIfRegExValidator" (preferably in a common location of the solution ie. either in Model or a Common project, as applied) and copy below code:
public class RequiredIfNotRegExValidator : ValidationAttribute
{
private RequiredAttribute _innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }

public RequiredIfNotRegExValidator(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.DependentProperty);

if (field != null)
{
var phoneNumber = Convert.ToString(value, CultureInfo.CurrentCulture);

// get the value of the dependent property
object dependentValue = field.GetValue(validationContext.ObjectInstance, null);

// trim spaces and convert dependent value to uppercase to support case senstive comparison
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
dependentValue as string).Length == 0 ? null : (dependentValue as string).ToUpper();
}

// trim spaces and convert TargetValue to uppercase to support case senstive comparison
if (TargetValue != null && TargetValue is string)
{
TargetValue = (TargetValue as string).Trim();
TargetValue = (TargetValue as string).Length == 0 ? null : (TargetValue as string).ToUpper();
}

// compare the value against the target value
if ((dependentValue == null && TargetValue.Equals("") ||
(dependentValue == null && !TargetValue.Equals("") ||
(dependentValue != null && !dependentValue.Equals(this.TargetValue)))))
{
// try validating this field
if (!_innerAttribute.IsValid(value))
{
     var match = _regex.Match(phoneNumber);
     if (!match.Success)
           // validation failed - return an error
           return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
}
// validation success - return success
return ValidatioResult.Success;
}
}
We need to create or make changes to Model(s) and Controller(s) as below to implement the created custom validation.

POCO / Model: Create or Modify Address class to apply the custom validation on City property as below to define City is required when selected Country is USA.
public class Address {
public int AddressId {get; set; }

public string Line1 { get; set; }

public string Line2 { get; set; }

public string City { get; set; }

public string State { get; set; }

public string Zip { get; set; }

public IEnumerable Country { get; set; }

[RequiredIfRegExValidator(@"^\d{10}$", "Country", "USA", ErrorMessage = "Phone Requires Numbers between 0-9")]
public string Phone { get; set; }
}
Controller: The controller for Address entity with a POST method will look like below.

Here, before persisting the changes in database, I am forcing process to re-validate Modal State by calling "this.Validate()", which will help the process to identify and throw an error upfront instead of making a call to DB.
public class AddressController : ApiController
{
[ResponseType(typeof(Address))]
public IHttpActionResult PostAddress(Address address)
{
// use below to force validation before doing anything
this.Validate(address);

if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Address.Add(address);
db.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = address.AddressId }, address);
}
}
Testing: Below TestMethods will help testing the post method to check for the expected validation error:

Here, The first test method will represent a case forcing this.Validate() method and second without forcing this.Validate() in controller's POST method.
// Forcing this.Validate() - this case Controller will thow the error
[TestMethod]
public void RequiredPhoneinNumbersWhenCountryIsNotUSATest()
{
Address address = new Address { Line1 = "200 E Main St", Line2 = "Apt B", State = "VA", Country = "USA", Phone="732654ABC" };
AddressController addressController = new AddressController();
AddressController.Request = new HttpRequestMessage();
AddressController.Request.Properties["MS_HttpConfiguration"] = new HttpConfiguration();

addressController.PostAddress(address);

Assert.IsFalse(addressController.ModelState.IsValid);
Assert.IsTrue(addressController.ModelState.Count == 1, "Phone Requires Numbers between 0-9");
}
// Without forcing this.Validate() - this case DB will throw the error
[TestMethod]
public void RequiredPhoneinNumbersWhenCountryIsNotUSATest()
{
Address address = new Address { Line1 = "200 E Main St", Line2 = "Apt B", State = "VA", Country = "USA", Phone="732654ABC" };
try
{
AddressController addressController = new AddressController();
AddressController.Request = new HttpRequestMessage();
AddressController.Request.Properties["MS_HttpConfiguration"] = new HttpConfiguration();

addressController.PostAddress(address);
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Assert.AreEqual("Phone Requires Numbers between 0-9", validationError.ErrorMessage);
}
}
}
}
With this I am concluding the illustration. Feel free to share your feedback.

Happy Programming !!!

Monday, January 9, 2017

MVVM Pattern

The Model-View-View Model is a natural pattern which will provide Separation of Concerns for XAML platforms like WPF. Below are some of the advantages of using this pattern:

  • It provides separation of concerns. A clean separation between application logic and the UI will make an application easier to test, maintain, and evaluate.
  • It improves code re-use opportunities and enables the developer-designer workflow.
  • When the UI XAML is not tightly coupled to the code-behind, it is easy for designers to exercise the freedom they need to be creative and make a good product.
  • It increases application's test-ability. Moving the UI logic to a separate class that can be instantiated independently of a UI technology makes unit testing much easier.

There are three core components in the MVVM pattern: the Model, the View, and the View Model. Each serves a distinct and separate role. Below explains the relationship between these three components (image courtesy MSDN):

The components are decoupled from each other, thus enabling: Components to be swapped, Internal implementation to be changed without affecting the others, Components to be worked on independently, and Isolated unit testing.

At a high level, the components interaction happens as, the view "knows about" the view model, and the view model "knows about" the model, but the model is unaware of the view model, and the view model is unaware of the view.

View: The View is responsible for defining the structure, layout, and appearance of what the user sees on the screen. This is defined purely with XAML with limited code-behind that does not contain business logic. A view can have its own view model, or it can inherit its parent's view model, and gets data through bindings, or by invoking methods on the view model.

Model: This is the representation of the Domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

View Model: This acts as an intermediary between the View and the Model, and responsible for handling the view logic. Typically, the view model interacts with the model to retrieve data and then makes the data available to the view by reformat the data simpler for the view to handle. The view model may also be responsible for defining logical state changes that affect some aspect of the display in the view, such as an indication that some operation is pending.

Sunday, January 8, 2017

Repository Pattern

Repository Pattern separates the data access logic and maps it to the entities in the business logic by working with the domain entities and performing data access logic. The interaction between domain entities, data access logic and the business logic talk to each other using interfaces, and hides the details of data access from the business logic. In other words, business logic can access the data object without having knowledge of the underlying data access architecture.

Using this pattern, business logic is not aware whether the application is using LINQ to SQL or ADO.NET Entity Model ORM. In the future, underlying data sources or architecture can be changed without affecting the business logic.

Some advantages of using Repository Pattern are: Easy Domain driven development, can test business and database access logic separately, no duplication of code and maintainability of code is easy as data access logic is centralized.

Repository Pattern illustration:
As a First step we will create a base Entity interface with common properties, a Book Entity and a Base repository interfaces with CRUD operations
// Entity Base Interface with common properties
public interface IEntityBase
{
public int ID { get; set; }
public DateTime? CreateDate { get; set; }
public DateTime? ModifiedDate { get; set; }
}

// Base Repository Interface with CRUD operations
public interface IBaseRepository where T: IEntityBase
{
IEnumerable All();
T Create(T entity);
void Update(T entity);
T Delete(T entity);
int? Save();
}

// Book Entity implementing IEntityBase
public class Book : IEntityBase
{
public string Title { get; set;}
public decimal Price { get; set;}
}
Generic Implementation of Repository Pattern
Create BookRepository class by inheriting IBaseRepository as below:
public class BookRepository : IBaseRepository where T : IEntityBase
{
private DotNetLearningContext context;
protected readonly IDbSet _dbset;

public BookRepository(DotNetLearningContext context)
{
this.context = context;
this._dbset = context.Set();
}

public virtual IEnumerable All()
{
return _dbset.AsEnumerable();
}

public IEnumerable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
IEnumerable query = _dbset.Where(predicate).AsEnumerable();
return query;
}

public virtual T Create(T entity)
{
return context.Set().Add(entity);
}

public virtual void Update(T entity)
{
context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}

public virtual T Delete(T entity)
{
return context.Set().Remove(entity);
}

public async Task Save()
{
return await context.SaveChangesAsync();
}
}
You can use / call this repository class as below:
IBaseRepository bookRepository = new BookRepository();
var result = bookRepository.All;

foreach (var r in result)
{
Console.WriteLine(r.authorname);
}
Dependency Injection Implementation of Repository Pattern
Create BaseRepository class by inheriting IBaseRepository as below:
public class BaseRepository : IBaseRepository where T : IEntityBase
{
private DotNetLearningContext context;
protected readonly IDbSet _dbset;

public BaseRepository(DotNetLearningContext context)
{
this.context = context;
this._dbset = context.Set();
}

public virtual IEnumerable All()
{
return _dbset.AsEnumerable();
}

public IEnumerable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
IEnumerable query = _dbset.Where(predicate).AsEnumerable();
return query;
}

public virtual T Create(T entity)
{
return context.Set().Add(entity);
}

public virtual void Update(T entity)
{
context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}

public virtual T Delete(T entity)
{
return context.Set().Remove(entity);
}

public async Task Save()
{
return await context.SaveChangesAsync();
}
}
Using UnityContainer Register and Resolve Interface and Class implementations to make it available to use as Dependency Injection(s) as below in App/WebApiConfig classes:
// Dependency Injecor Resolvers
var container = new UnityContainer();

container.RegisterType(typeof(IBaseRepository<>), typeof(BaseRepository<>));

config.DependencyResolver = new UnityResolver(container);
Inject resolved repositories through controllers as below :
public class BookController
{
public BookController(IBaseRepository baseRepository)
: base(baseRepository)
{
// Call Base Repository Methods to use
}
}