VS Live is Coming to Chicago this May! Special Discount for ALM User Group & Friends

by Angela March 01 2013 10:29

email header2

So in case you haven’t noticed, Visual Studio Live is coming back to Chicago after many, many years of not being here.  This makes me very happy because a) I don’t have to pay for a flight and hotel in L.A. or Seattle, and b) well, see a) because cost is one factor that makes attending great conferences like this so hard to do for some of us.  Regular price of admission is $1,995 for the full 4 days, which isn’t bad when you think of all the awesome content you get.  Early bird registration ends soon and saves you $300 but wait, there’s more! Actually it’s more discount that I can give you.

In case you did not make it out to the last Chicago Visual Studio ALM User Group you may have missed out on the discount code that I was able to get for all of you.  Sign up right now using the links in this email (or the code UGCH1) and you’ll save $500 off of the $1995 registration too, so it would be only $1495 for the full 4 day pass! 

  • Visual Studio Live! Chicago tracks include:
  • ASP.NET
  • Azure / Cloud Computing
  • Cross-Platform Mobile
  • Data Management
  • HTML5 / JavaScript
  • SharePoint / Office
  • Windows 8 / WinRT
  • WPF / Silverlight
  • Visual Studio 2012 / .NET 4.5

 

So no travel costs, no hotel stay, AND save 25%. How can you NOT go? Hope to see you at our next meeting, and at VS Live Chicago this May!

Tags:

ALM | Application Lifecycle Management | Azure | Entity Framework | MSDN | TFS 2012 | Visual Studio 2012 | git | development | Visual Studio | Team Foundation Server | Cloud Computing | HTML5 | Silverlight | .NET 4.5 | VS Live

N-Tier Entities with Entity Framework Code First, Part 1

by JoshGillespie April 23 2012 16:29

I’ve been working for a client for on a 3-tiered application for awhile now.  The tiers are physically separate machines.  It has a web tier, application tier, and data tier.

The application tier is a bunch of WCF services and we’ve been using Entity Framework just for the DAL (the “standard” way with an EDMX file). The entities are not exposed past the service boundary, because we didn’t want to “leak” an Entity Framework dependency beyond the services.  We have created WCF Data Contracts for the service operations and translate the entities to/from the contracts at the service boundary. Our typical bottom-to-top operation looks like this

  • Entities, which are translated into
  • Data Contracts, are sent to the calling application and then translated into
  • View Models, which are specific to one view and one view alone.

I’ve been playing with Entity Framework 4.3 and really enjoyed the clean separation it enables.  I wanted to see if it was now possible to send Entity Framework entities beyond the service boundary and isolate the EF dependencies.  I am happy to report that is not only possible, it is easy. 

Here I have a simple solution for a 3-tier application.

Solution explorer screenshot

Each project is pretty simple and the purpose of each is pretty obvious, save for two of them.

  • NTierEF.Contracts is a class library that will contain our entity definitions. This is the only project shared between the tiers. This is also where where we’ll put the interface definition for the WCF service.
  • NTierEF.Contracts.Internal is a class library that contains interfaces between our WCF Service and Data Access Layer projects.

I’m using the AdventureWorks database, and in this post I’m going to show you how to setup the entities and Data Access Layer.

I’ll start with a very simple entity definition for the “Contact” entity.  It belongs in the Contracts project, as this is the bit that crosses the service boundary. I’ve included some simple validations using the annotations.

namespace NTierEF.Contracts.Entities.Person
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Runtime.Serialization;
    using System.Security.Cryptography;
    using System.Text;

    [DataContract]
    public class Contact
    {
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        [DisplayName("Use Eastern Name Style?")]
        [Required]
        public bool NameStyle { get; set; }

        [DataMember]
        [StringLength(8)]
        public string Title { get; set; }

        [DataMember]
        [DisplayName("First Name")]
        [StringLength(50)]
        [Required]
        public string FirstName { get; set; }

        // Snipping for brevity
    }
}

Next, I need a DbContext implementation. This defines what entity collections are available.Entity Framework uses an IDbSet<T> collection for each entity, but that is an EF specific dependency. To keep the EF dependency contained, I’ve created a very simple repository-like interface that exposes the DbSet collections as IQueryables. The interface goes in our Internal.Contracts project.

    public interface IDbContext
    {
        IQueryable<Contact> Contacts { get; }
        T Add<T>(T entity) where T : class;
        T Edit<T>(T entity) where T : class;
        void Save();
    }

The DbContext merely exposes the IDbSets as IQuerable.

    public class SqlDataAccess : DbContext, IDbContext
    {
        public IDbSet<Contact> Contacts { get; set; }
        
        IQueryable<Contact> IDbContext.Contacts { get { return this.Contacts; } }
        
        public T Add<T>(T entity) where T:class
        {
            var set = this.Set<T>();
            set.Add(entity);
            this.SaveChanges();
            return entity;
        }

        public T Edit<T>(T entity) where T : class
        {
            var set = this.Set<T>();
            set.Attach(entity);
            this.Entry<T>(entity).State = System.Data.EntityState.Modified;
            this.SaveChanges();
            return entity;
        }

        public void Save()
        {
            this.SaveChanges();
        }
    }

Next is the mapping file. We could almost rely on the the conventions, but the AdventureWorks database uses schemas other than “dbo”, so I need a mapping file. I could use the annotations, but that “leaks” an EF dependency into the entities, so I’m taking advantage of the separate mapping files and the Fluent API.

This includes a little more than the bare minimum, but shows how to mark up the various properties. 

public class PersonContactMapping : EntityTypeConfiguration<Contact>
{
    public PersonContactMapping()
    {
        HasKey(e => e.Id);
        ToTable("Contact", "Person");
        Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.HasColumnName("ContactId");
        Property(e => e.NameStyle).IsRequired();
        Property(e => e.Title).HasMaxLength(8);
        Property(e => e.FirstName).HasMaxLength(50).IsRequired();
        Property(e => e.MiddleName).HasMaxLength(50);
        Property(e => e.LastName).HasMaxLength(50).IsRequired();
        Property(e => e.Suffix).HasMaxLength(10);
        Property(e => e.EmailAddress).HasMaxLength(50);
        Property(e => e.EmailPromotion).IsRequired();
        Property(e => e.Phone).HasMaxLength(25);
        Property(e => e.PasswordHash).HasMaxLength(128).IsRequired();
        Property(e => e.PasswordSalt).HasMaxLength(10).IsRequired();
        Property(e => e.RowGuid).IsConcurrencyToken();
        Property(e => e.ModifiedDate).IsRequired();
    }
}
Because it is specific to the store and depends on the Entity Framework DLLs, it belongs in the DAL project. We take that mapping class and plug it into the DbContext using the OnModelCreating override…
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new PersonContactMapping());
        base.OnModelCreating(modelBuilder);
    }

And now I have a POCO entity mapped to an existing database schema. The EF dependencies have been isolated by using the separate mapping files and a simple interface over the data context class.

Setting up subsequent entities follows the same pattern. POCO Entity in the Contracts project, mapping file in the data layer project, wired up in the DbContext. So, for example, to add the address to the application, I’ll add a new POCO class.

public class Address
    {
        public int Id { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
        public StateProvince State { get; set; }
        public string PostalCode { get; set; }
        public Guid RowGuid { get; set; }
        public DateTime ModifiedDate { get; set; }
    }

And a new mapping…

public class PersonAddressMapping : EntityTypeConfiguration<Address>
    {
        public PersonAddressMapping()
        {
            ToTable("Address", "Person");
            HasKey(e => e.Id);
            Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(e => e.AddressLine1).HasMaxLength(60).IsRequired();
            Property(e => e.AddressLine2).HasMaxLength(60);
            Property(e => e.City).HasMaxLength(30).IsRequired();
            Property(e => e.PostalCode).HasMaxLength(15).IsRequired();
            Property(e => e.RowGuid).IsConcurrencyToken();
            Property(e => e.ModifiedDate).IsRequired();

            HasRequired(e => e.State).WithMany().Map(config => config.MapKey("StateProvinceID"));
        }
    }

And include it in the DbContext class by adding an IDbSet<Address> collection property, an IQueryable<Address> collection property (don’t forget to add that to the interface too), and add the new Mapping file to the OnModelCreating method.

In the next post, I’ll create the WCF service and expose our new entities across the service boundary.

Tags: , , , ,

Blogging | Entity Framework | Entity Framework Code First