Tips and Tricks in a world of Mix

You can check out the series of the posts on the subject

<—SPA 2 Technologies&Patterns 

 SPA 4 Surfacing JSON Data with ASP.NET Web API—>

Data Layer Technologies

image

  • SQL Server CE
  • ORM                   Using Entity Framework Code First (version 5)

                  Data stored and save to its own context (DBContext)

image

 

 

Models are simple classes without any additional references.

 

Creating a Model

Data containers – define your data and vehicle for you data

Domain objects

POCO– plain old class(CLR) object

Don’t have additional references – Independent and stand alone objects

makes them ease to  pass around across domain –

through the EF(fills the POCO up)  –> Repositories –> UoW –> WebAPI

 

So we can define a SessionBrief object to contain a short minimum data to revive the program when fails and some more robust and full object to init the program fully after the primamry reviving. All that through inj=heritance

 

image

 

Model Diagram

 

image

 

You can set [Key] attribute for EF to understand the key property

 

DBContext

Defines relations between Models And Database

Stores objects and changes in its context (in memory)

 

Defines Sets of Data – DBSet<T>

Configuring the DBContext –

    

image

 

Defining Conventions with the DBContext

 

  • One to Many connection

Connecting unique Speaker to multiple sessions

Doing it through list property on a persons POCO model.

(in my opinion can be added to speaker class instead)

 

   1: public class SessionConfiguration : EntityTypeConfiguration<Session>

   2:   {

   3:       public SessionConfiguration()

   4:       {

   5:           // Session has 1 Speaker, Speaker has many Session records

   6:           HasRequired(s => s.Speaker)

   7:              .WithMany(p => p.SpeakerSessions)

   8:              .HasForeignKey(s => s.SpeakerId);

   9:       }

  10:   }

  11: }

 

  • A Many-to-Many example – Sessions to  Persons through Attendance

There can be few persons attending few sessions – the key

 

   1: public class AttendanceConfiguration : EntityTypeConfiguration<Attendance>

   2:    {

   3:        public AttendanceConfiguration()

   4:        {

   5:            // Attendance has a composite key: SessionId and PersonId

   6:            HasKey(a => new { a.SessionId, a.PersonId });

   7:  

   8:            // Attendance has 1 Session, Sessions have many Attendance records

   9:            HasRequired(a => a.Session)

  10:                .WithMany(s => s.AttendanceList)

  11:                .HasForeignKey(a => a.SessionId)

  12:                .WillCascadeOnDelete(false);

  13:  

  14:            // Attendance has 1 Person, Persons have many Attendance records

  15:            HasRequired(a => a.Person)

  16:                .WithMany(p => p.AttendanceList)

  17:                .HasForeignKey(a => a.PersonId)

  18:                .WillCascadeOnDelete(false);

  19:        }

  20:    }

  21:  

 

the key is to have a connecting model between them two

   1: public class Attendance

   2:    {

   3:        public int PersonId { get; set; }

   4:        public Person Person { get; set; }

   5:        

   6:        public int SessionId { get; set; }

   7:        public Session Session { get; set; }

   8:  

   9:        /// <summary>Get and set the person's rating of the session from 1-5 (0=not rated).</summary>

  10:        [Range(0,5)]

  11:        public int Rating { get; set; }

  12:  

  13:        /// <summary>Get and set the person's session evaluation text.</summary>

  14:        public string Text { get; set; }

  15:    }

Here we can see that there are two properties of ID type – one for session and the second for person.

So through the connection of attendance activity we are connecting multiple persons to multiple sessions.

 

All that is connected in DBContext

 

  • Establish Seed Data – creating basic data if the db doesn’t exist (good for development and debugging on unattached environments) through SetInitializer of Database
  • Define conventions – plural/singular table names
  • Adding the configurations for Model Relationships as described before

 

   1: public class CodeCamperDbContext : DbContext

   2:    {

   3:        // ToDo: Move Initializer to Global.asax; don't want dependence on SampleData

   4:        static CodeCamperDbContext()

   5:        {

   6:            Database.SetInitializer(new CodeCamperDatabaseInitializer());

   7:        }

   8:  

   9:        public CodeCamperDbContext()

  10:            : base(nameOrConnectionString: "CodeCamper") { }

  11:  

  12:        protected override void OnModelCreating(DbModelBuilder modelBuilder)

  13:        {

  14:            // Use singular table names

  15:            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

  16:  

  17:            modelBuilder.Configurations.Add(new SessionConfiguration());

  18:            modelBuilder.Configurations.Add(new AttendanceConfiguration());

  19:        }

  20:  

  21:        public DbSet<Person> Persons { get; set; }

  22:        public DbSet<Session> Sessions { get; set; }

  23:        public DbSet<Attendance> Attendance { get; set; }

  24:  

  25:        // Lookup Lists

  26:        public DbSet<Room> Rooms { get; set; }

  27:        public DbSet<TimeSlot> TimeSlots { get; set; }

  28:        public DbSet<Track> Tracks { get; set; }

  29:    }

 

 

Repository Pattern – Why?

Maintenance  – Data access code is easy to find , debug an d change

Code Reuse – brake down the functionality , concentrate the code

Focused on getting and saving data

Consistent API

Single Responsibility Principle (SRP) pattern – have each of your classes to concentrate on one thing only

 

Make a simple consistent API matched for any type

 

   1: public interface IRepository<T> where T : class

   2:    {

   3:        IQueryable<T> GetAll();

   4:        T GetById(int id);

   5:        void Add(T entity);

   6:        void Update(T entity);

   7:        void Delete(T entity);

   8:        void Delete(int id);

   9:    }

 

EFRepository –

  • Generalizing a set of ordinary functionality for each model , so we shouldn’t write it specific for each of them.
  • It implements IRepository – It allows you to abstract the types in additional layer, even though it’s not a necessary. Allows to use LINQ queries.
  • And we’ll have additional Interfaces for each Model when it’ll be a specific functionality per Model, or a DTO arrangement that will rearrange and minify the amount of data that will be passed.
  • We also can inherit from EFRepository but override the functions to match the specific scenario for our Model.
  • The EFRepository encapsulates the DBContext   and exposes functionality to deal with it.
  • Interactions with DBContext  through the EF  abilities.

 

Uow – Unit of Work –

 

image

 

Through the Factory Pattern it builds the wright repositories concluded by the given type.

   1: public class CodeCamperUow : ICodeCamperUow, IDisposable

   2: {

   3:     // Code Camper repositories

   4:     // You can add here your types easily

   5:     public IRepository<Room> Rooms { get { return GetStandardRepo<Room>(); } }

   6:  

   7:     /// Save pending changes to the database

   8:     public void Commit()

   9:     {

  10:         //System.Diagnostics.Debug.WriteLine("Committed");

  11:         DbContext.SaveChanges();

  12:     }

  13:  

  14: }

  15:  

  16:  

  17: //and you'll call the UoW from Controllers like this :

  18:  

  19:  

  20: public class LookupsController : ApiControllerBase

  21:  {

  22:      public LookupsController(ICodeCamperUow uow)

  23:      {

  24:          Uow = uow;

  25:      }

  26:  

  27:      // GET: api/lookups/rooms

  28:      [ActionName("rooms")]

  29:      public IEnumerable<Room> GetRooms()

  30:      {

  31:          return Uow.Rooms.GetAll().OrderBy(r => r.Name);

  32:      }

  33: ...

  34:  

  35: }

 

So you can organize and rearrange the repositories inside the UoW and that’s the methods that will be called from the WebAPI layer .

 

You can check out the series of the posts on the subject

<—SPA 2 Technologies&Patterns 

 SPA 4 Surfacing JSON Data with ASP.NET Web API—>

Comments on: "SPA 3–JOHN PAPA– Data Models, Entity Framework, and Data Patterns of the Code Camper SPA" (2)

  1. […] SPA 3– Data Models, Entity Framework, and Data Patterns –> […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: