Awhile back I wrote a simple Holiday service to try out Entity Framework "Code First" (the new name for Code Only). I’ve upgraded the bits and tried out some of the new features of CTP3 using this walkthrough as a guide. You can download my sample app from git hub.
In addition, I added Inversion of Control (IOC) using Castle Windsor and implemented a repository pattern.
My database generation script and test data now look like this.
databasefactory.Create(); var repository = new HolidayRepository(databasefactory); //... build up test data for xmas and newyear repository.Add(xmas); repository.Add(newYear); //commit changes var unitOfWork = new UnitOfWork(databasefactory); unitOfWork.Commit();
The other interesting part of this sample project is using WCF and EF together and WCF dependency injection using Castle Windsor.
First I setup my interfaces and configuration files for EF and WCF.
[DataContract]
public class Holiday : IEntity
{
public long Id { get; set; }
[DataMember]
public string HolidayName { get; set; }
[DataMember]
public DateTime HolidayDate { get; set; }
[DataMember]
public ICollection<holidayevent> HolidayEvents {get; set;}
}
[DataContract]
public class HolidayEvent : IEntity
{
public long Id { get; set; }
[DataMember]
public string EventName { get; set; }
[DataMember]
public Holiday Holiday { get; set; }
[DataMember]
public long HolidayId { get; set; }
}
public HolidayConfiguration()
{
Property(h => h.Id).IsIdentity();
Property(h => h.HolidayName).HasMaxLength(1000).IsRequired();
Relationship(e => e.HolidayEvents).FromProperty(h => h.Holiday);
}
public HolidayEventConfiguration()
{
Property(e => e.Id).IsIdentity();
Property(e => e.EventName).HasMaxLength(1000).IsRequired();
//HolidayId is a FK property and Holiday is a navigation property backed by this FK
Relationship(e => e.Holiday).FromProperty(h => h.HolidayEvents).HasConstraint((e, h) => e.HolidayId == h.Id);
}
In my .svc file I use a custom factory to do dependency injection
Factory="Castle.Facilities.WcfIntegration.WindsorServiceHostFactory, Castle.Facilities.WcfIntegration"
On startup, I add my HolidayService as a component and add the DatabaseFactory as a parameter. The DatabaseFactory is used to setup my EF Object Context.
container.Register(Component.For<iholidayservice>().ImplementedBy<holidayservices>().DependsOn
(Property.ForKey("databaseFactory").Eq(databaseFactory)));
A great resource for seeing many of the new features in EF CTP3 is the shrinker project. This is where I found many great examples of property facets and relationships using Entity Framework.
