Wednesday, 5 August 2015

MVC: Data Validations

Entity Framework
- part of the .Net framework
- allows you to access a relational database with strongly-typed LINQ queries, or VB code, or really any .Net language.

LINQ - Language Integrated Query
- feature that's in both C# and VB.

Ways to start with EF
  • Schema First - you open up a graphical designer in VS, point it to an existing database, and it can import the database schema, and generate all the classed you need to query and update that database.
  • Model First - you use the same graphical designer in VS to draw a conceptual model for your app, what classes you want. EF will generate both your class definitions and the database schema.
  • Code First - you write C# classes and the EF can use those class definitions to create a database for you.
Notes:
- create the classes for entities in Models folder. You may consider having a separate folder or even a separate project where you define the entities.
- create a class to persist and retrieve this data. It needs to derive from an Entity Framework class known as DBContext. Add DBSets.

public class OdeToFoodDB : DBContext
{
     public DBSet<Restaurant> Restaurants {get; set;}
     public DBSet<Restaurant> Restaurants {get; set;}
}

On the Home Controller, instantiate your new class, and point out that this is a disposable resource.

OdeToFoodDB _db = new OdeToFoodDB();

protected override void Dispose(bool disposing)
{
     if (_db != null)
     {
          _db.Dispose();
     }
     base.Dispose(disposing);
}

In your view, Index.cshtml

@model IEnumerable<OdeToFood.Models.Restaurant>
@foreach (var item in Model)
{
    <div>
            <h4>@@item.Name</hr>
           <div>@item.City, @item.Country</div>
    </div>
}


public ICollection<RestaurantReview> Reviews {get; set:}

No comments:

Post a Comment