Tag Archives: EF6

EF6 or EF Core? How Do I Choose?

In late October, I spoke at DevIntersection. One of my sessions was called EF6 or EF Core? How Do I Choose? As I’ve been an authority on EF since it’s earliest days, people have been asking me this question frequently, which inspired the talk.

The session was not recorded but I’m sharing my slides on SlideShare. I go into detail on the topic in my upcoming Pluralsight course, “EF Core: Getting Started” which I am currently building. Watch my Pluralsight author page (as well as twitter.com/julielerman and this blog!) for its release.

In the meantime, here is a link to the slides from the DevIntersection talk.ef6-or-ef-core

Completely New EF in the Enterprise Course on Pluralsight

My baby is here! A brand new Entity Framework in the Enterprise.

[See also:  New EF Core Course on Pluralsight!]

In 2012, I published a course on Pluralsight called Entity Framework in the Enterprise. Since then I have learned so much, most importantly, I’ve become very active with Domain-Driven Design, even publishing the DDD Fundamentals course that I co-created with Steve Smith. This has had a big impact on how I think about designing and architecting software and in turn,how I approach incorporating EF in to large, complex applications.

I’ve been wanting to re-do that old course to share my new views. I finally began in January of this year, but had a 3 month conference travel hiatus. So while it feels like a baby that I spent 9 months on, it was really only 6 months. Still quite a long time!

The course is now live! Entity Framework in the Enterprise

In the course, I use VS2015 and EF6. Why EF6? Because EF Core is too new. Most of the patterns I discuss and demonstrate are totally applicable to EF Core. There is one thing that is not yet in EF Core: Value Objects, but that is coming. Also the module on testing focuses on mocking and does not take EF Core’s new In Memory provider into account. Other than that, you can use what you learn here with EF Core as well.

I put a lot of thought into this course and I think this comment on the discussion forum for the course expresses it so well:

I just watched Julie Lerman’s prior Entity Framework in the Enterprise three weeks ago, before this new course was released, and boy am I glad she’s updated the course. I had thought the previous version was a bit dated (2016 vs 2012 & EF6 vs EF4) and a bit basic with what Julie refers to as Demo Ware. This updated course goes into more details about architecting projects, improved Moq testing with EF6, and a better explanation of DDD with Bounded Contexts using Schema to segregate areas. I already had a good understanding of EF, DDD, Repositories, UoW, and CQRS before watching and while I wouldn’t set up things 100% this way in my own applications they did jump start some refactorings and rethinking on how I maintain my solution, which is the purpose of these courses, to give fresh ideas as technology evolves, just as Entity Framework has. Thanks for updating the course and for those who have watched the previous version, definitely give this new one a watch.

image

Upcoming EF Course on Pluralsight

9/14: I’ve been told “a few more business days”. Believe me I’m as eager as anyone can be for this to get released! 🙂

9/23: It’s here!!! 

https://app.pluralsight.com/library/courses/entity-framework-enterprise-update/table-of-contents

At the beginning of the year, I started dong a completely new version of my EF in the Enterprise course. That one is years old and was done with EF4 before DbContext and Code First even existed. Also before I started learning about Domain Driven-Design.

I had a lot of side-tracks in my schedule along the way including 3 months of conference travel and  a lot of hard thinking about how to explain and demonstrate some of these concepts. But I’ve finally finished the last module yesterday. I have some work to do in response to tech reviews of some of the module and I have to do the dreaded task of coming up with the questions for a few of the modules. But then it will be ready for Pluralsight to push through and get published. I don’t think it will be long now.

While I used EF6 for this course, most of the ideas also apply to EFCore as well.

In the meantime, I can tell you the titles of the 8 modules of this course which seems to have come out a little under 5 hours total:

  1. Architecting a Data Layer
  2. Understanding EF Encapsulation and the Great Repository Debates
  3. Implementing Encapsulation Patterns with EF6
  4. Managing Complex Domains and Data Models: Lessons from DDD Bounded Context
  5. Refactoring to Domain-Driven Design Bounded Contexts:A Walkthrough
  6. Handling the State of Disconnected Graphs
  7. Mapping DDD Domain Models with Entity Framework
  8. Testing Your Apps When Entity Framework is Involved

Watch this space for the new course: bit.ly/PS-Julie

Using JSON Data and EF Core to Seed a Database

I’m so used to use standard code (C# and EF APIs) to let EF help me seed a database. You know, instantiate an object, populate its fields, maybe add objects to a related list. Then add the whole kit n’ kaboodle to the DbContext and call SaveChanges.

I was showing some EF Core code to Geoffrey Grossenbach when we were talking about doing a Play by Play for Pluralsight on EF Core in advance of my buckling down to do a more serious course. Geoffrey looked at all the code for building up my objects to seed the database and said “wow that’s a lot of code. Can’t you use JSON or something?” (Note: I tired of trying to get this code formatted prettily in wordpress, but you get the point…right?)

private static List BuildWeatherEvents()
{
  var events = new List
  {
   WeatherEvent.Create(DateTime.Now,WeatherType.Sun,
    new List<string[]>{new []{"Julie","Oh so sunny!"}}),
   WeatherEvent.Create(DateTime.Now.AddDays(-2),WeatherType.Rain),
   WeatherEvent.Create(DateTime.Now.AddDays(-3),WeatherType.Sun,
    new List<string[]>{
      new []{"Julie","Oh lovely summer sun!
                      Too bad I'm on my computer"},
      new []{"Everyone in vermont", "Hooray let's go play!"},
      new []{"Sampson","I'd like to go for a swim, please!"},
    }),
   WeatherEvent.Create(DateTime.Now.AddDays(-4),WeatherType.Cloudy),
   WeatherEvent.Create(DateTime.Now.AddDays(-5),WeatherType.Rain),
   WeatherEvent.Create(DateTime.Now.AddDays(-6),WeatherType.Sun)
  };
 var lastEvent = 
   WeatherEvent.Create(DateTime.Now.AddDays(-1),  WeatherType.Snow,
          new List<string[]> {
             new[] { "Julie", "Snow? In July? 
                      Okay this is ridiculous even for VT!" } });
 lastEvent.Reactions.FirstOrDefault().Comments.Add
     (new Comment { Text = "Get over it, Julie!" });
 events.Add(lastEvent);
 return events;
}

Oh how much prettier it would be. Here’s how I’ve done it with EF Core but you can certainly use the same concept for doing the same with EF6.

My domain is WeatherEvent which is the domain in my EFCore demo at https://github.com/julielerman/EFCore-ASPNetCore-WebAPI-RTM, (which I have not yet updated to demonstrate using the JSON data).

Here’s the json which I store in a file called weatherdataseed.json.

[
 {
  "date": "2016-07-27T00:00:00",
  "time": "22:09:13.8216230",
  "type": 5,
  "reactions": [
   {
    "name": "Julie",
    "quote": "Oh so sunny!",
    "comments": []
   }
  ],
 "mostCommonWord": null
 },
 {
 "date": "2016-07-25T00:00:00",
 "time": "22:09:13.8237230",
 "type": 1,
 "reactions": [],
 "mostCommonWord": null
 },
 {
  "date": "2016-07-24T00:00:00",
  "time": "22:09:13.8238740",
  "type": 5,
  "reactions": [
   {
    "name": "Julie",
    "quote": "Oh lovely summer sun! Too bad I'm on my computer",
    "comments": []
   },
   {
    "name": "Everyone in vermont",
    "quote": "Hooray let's go play!",
    "comments": []
   },
   {
    "name": "Sampson",
    "quote": "I'd like to go for a swim, please!",
    "comments": []
   }
  ],
  "mostCommonWord": null
 },
 {
  "date": "2016-07-23T00:00:00",
  "time": "22:09:13.8239130",
  "type": 6,
  "reactions": [],
  "mostCommonWord": null
 },
 {
  "date": "2016-07-22T00:00:00",
  "time": "22:09:13.8239210",
  "type": 1,
  "reactions": [],
  "mostCommonWord": null
 },
 {
  "date": "2016-07-21T00:00:00",
  "time": "22:09:13.8239290",
  "type": 5,
  "reactions": [],
  "mostCommonWord": null
 },
 {
  "date": "2016-07-26T00:00:00",
  "time": "22:09:13.8239360",
  "type": 2,
  "reactions": [
   {
    "name": "Julie",
    "quote": "Snow? In July? Okay this is ridiculous even for VT!",
    "comments": [
     {
     "text": "Get over it, Julie!"
     }
    ]
   }
 ],
 "mostCommonWord": null
 }
]

So that’s not just data, but hierarchical data with 3 levels of relationship. Expressing it in json is a lot easier and prettier and readable than building all of that up in C#, creating the objects, etc.

Now of course it’s time for the magical JSON.NET which makes it possible to pull this data in to EF short and sweet.

This is the full code that I’m using to seed the database from the JSON using EF.

I’m calling it from startup.cs in an ASP.NET Core Web API inside the Configure method. Here I’m just reading the file with System.IO.File.ReadAllText and then passing that text into my Seedit method. Also note the ConfigureServices where I’m setting up the DbContext along with the connection string it requires.

Note: There’s been some churn in the code in this post as  Shawn Wildermuth and I went through some learning on twitter with Dave Fowler, one of the core leads on the aspnet team. I  changed my original code to streamline it as per a great suggestion from Shawn, but Dave pointed out some scoping issues with that. So now the sample is back to my original version, where the seedit method is responsible for creating a new ServiceScope and instantiating the context. 

 public void ConfigureServices(IServiceCollection services)
 { 
   services.AddDbContext<WeatherContext>(
     options=> options.UseNpgsql(
       Configuration["Data:PostgreConnection:ConnectionString"]));
   services.AddMvc();
 }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseMvc();
  var dataText=System.IO.File.ReadAllText(@"weatherdataseed.json");
  Seeder.Seedit(dataText,app.ApplicationServices);
}

Here’s the Seedit method, which uses JSON.NET to deserialize the json into a list of  WeatherEvent objects.  The contract serializer is to overcome private setters in my WeatherEvent class. I got this from Daniel Wertheim’s github repo. Then I use the ASP.NET Core ServiceProvider to get service I set up in startup which will instantiate a WeatherContext along with the connection string specified in startup.

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using EFCoreWebAPI;
using Newtonsoft.Json;
using JsonNet.PrivateSettersContractResolvers;

public static class Seeder {
  public static void Seedit(string jsonData,
                            IServiceProvider serviceProvider) {
  JsonSerializerSettings settings = new JsonSerializerSettings {
    ContractResolver = new PrivateSetterContractResolver()
  };
  List<WeatherEvent> events =
   JsonConvert.DeserializeObject<List<WeatherEvent>>(
     jsonData, settings);
  using (
   var serviceScope = serviceProvider
     .GetRequiredService<IServiceScopeFactory>().CreateScope())
   {
     var context = serviceScope
                   .ServiceProvider.GetService<WeatherContext>();
     if (!context.WeatherEvents.Any()) {
       context.AddRange(events);
       context.SaveChanges();
     }
   }
 }
}

After instantiating the context, I have it check to see if I have any weather events in the database yet so I don’t re-seed. (This is logic I want for seeding during my demo so you may have different rules for the seeding.) Now I call context.AddRange passing in the list of WeatherEvent objects. I could use the DbSet directly or the context to call AddRange. And finally, SaveChanges.

So the key here, whether you are using EFCore or EF6 (so the use of the service is specific to the fact that my app is an ASPNET Core api), is really just reading the json file, deserializing the data and adding it to the context. This is oh, so much simpler than creating all of that data imperatively.

It may not always be the answer depending on the shape of your data but it was perfect for this particular model and the seed data that I needed.

 

Entity Framework, TimeSpan & SQL Server Time

In the “hey, you cant know everything” category….

A client asked me a question today about mapping TimeSpan to the Time data type in SQL Server.

I didn’t know there was a Time data type in SQL Server. I’m well aware of the Date data type we got in SS2008, but I skipped right past that other new type.

Since I never worked with a Time data type, I never had occasion to use it with EF. So when my client said something about timespan, I thought “that can’t be right”. Timespan is about intervals, not a point in time. Then he said something about the DateTime.TimeOfDay property which returns a timespan and I was all

bsi

So….

step 1:create a table in a SQL Server Database that has a Date field and a Time field.

image

step 2: reverse engineer to code first (I used the EF6 designer)

  public partial class SeparatedDateTime
    {        
        public int Id { get; set; }

        [StringLength(50)]
        public string somestring { get; set; }

        [Column(TypeName = "date")]
        public DateTime justDate { get; set; }

        public TimeSpan justTime { get; set; }
    }
ok so there it is: TimeSpan
step 3: write some code to test it out:
    private static void InsertSeparatedDateTime() {

      using (var context = new DateTimeTester()) {
        context.SeparatedDateTimes.Add(CreateSepDT());
        context.Database.Log = Console.WriteLine;
        context.SaveChanges();
      }
    }

    private static SeparatedDateTime CreateSepDT() {
      var sepDT = new SeparatedDateTime();
      sepDT.somestring = "A Test";
      sepDT.justDate = DateTime.Now.Date;
      sepDT.justTime = DateTime.Now.TimeOfDay;
      return sepDT;
    }
step 4: debug. 
check sepDT.justTime value and it looks like this : it is the milliseconds since midnight in many flavors
image
The log shows me that EF has transformed that value into a time value for the insert:
image
And surely it does the opposite when reading that data back out of the database.
Some caveats:
  • 24 hr time only
  • Presumes you calculated that timespan value correctly
  • All caveats associated with UTC
 
 
 
 
 

Recent Data Points Columns: Aurelia, Azure DocumentDB, Scriptcs, EF6, EF7, ASP.NET 5

Data Points – Aurelia Meets DocumentDB:
A Matchmaker’s Journey
(Part 1)

*Part 2 will be in Dec 2015 issue

Nov 2015

After exploring both DocumentDB and the new Aurelia framework, Julie Lerman decided it was time to use them together, but that proved more difficult than expected. Learn how she finally found the path to the correct solution.

Read article

Data Points – Revisiting JavaScript Data Binding — Now with Aurelia

Sep 2015

Julie Lerman has long been a fan of the Knockout JavaScript framework and its data binding talents. Here she explores the new Aurelia framework, which is quickly gaining momentum with Web developers, and finds that it offers a lot to like for data-oriented programmers.

Read article

Explore Entity Framework Behavior at the Command Line with Scriptcs

Jul 2015

Julie Lerman learns how to explore Entity Framework behavior interactively using Scriptcs.

Read article

An Overview of Microsoft Azure DocumentDB

Jun 2015

Julie Lerman takes a first look at the Microsoft entry into the document database field—Azure DocumentDB.

Read article

The EF6, EF7 and
ASP.NET 5 Soup

May 2015

Julie Lerman discusses the difference between the next version of .NET and what ASP.NET 5 apps will run on, then explains how Entity Framework 6 and Entity Framework 7 fit into the mix.

Read article

EF6 Code First Migrations for Multiple Models

Apr 2015

The new support for Code First Migrations in Entity Framework 6 makes it easier to store data for multiple models in a single database. But that support may not be what you imagine. Julie Lerman explains what this feature does and doesn’t do, and how to use it.

Read article

Looking Ahead to
Entity Framework 7

Jan 2015

In this first look at EF7, Julie Lerman discusses what EF7 will bring to developers, the motivations behind decisions being made about the framework, and what this version means to existing apps that use EF6 or earlier.

Read article

Getting Started with EF6 Course on Pluralsight

image

You may think you read that title wrong. Does she mean EF7? No, I actually invested some time into creating a new Getting Started with EF6 course even though EF6 was released about 18 months ago. When EF6 was released, most of what changed since EF5 was the advanced features and usage. I did a course called “EF6 Ninja Edition: What’s New in Entity Framework 6” specifically to cover those additions/improvements. But for the “toes in the water” first look at EF, not much had changed between EF5 and EF6 so the Getting Started with EF5 course remained pretty relevant.

Watch Getting Started with Entity Framework 6

So why Getting Started with EF6 now, when EF7 seems to be around the corner? Well, EF7 is still going to be a while. Even though a “Beta 6” was announced recently, the team has said in a significant way that EF7 Beta 6 is still “very much a preview” of EF7. A pre-release of EF7 is expected in early 2016 along with the release of ASPNET5. But the RTM of EF7 is still further off than that date. And even then, not everyone will be using EF7 right away.

So EF6 will be around for a long time and I decided that it was useful to have a course that addressed Getting Started with EF6 directly including using the latest version of Visual Studio – VS2015.

The first module is an overview which is designed for not just developers but even your managers who may want to have a better understanding of what EF is and how it fits into your overall plans.

I am also committed to creating two more EF6 courses for Pluralsight — also for the sake of being long-term resources. These will consolidate information in the various courses I’ve created about EF3.5 – 6 over the years. One will be an EF6 Fundamentals and the other will be Advanced EF6.

In the meantime, I’ll be updating the “Looking Ahead to EF7” course to reflect the Beta 6 since things have evolved since Beta 3 when I did that course.

EF6 Ninja Edition Course is Live on Pluralsight

It’s been a long haul and a long wait. I started work on this course, then switched gears to work on the Domain–Driven Design Fundamentals course with Steve Smith. When I returned to work on the EF6 course, a number of minor releases and patch releases had been published so I had to revise much of what I had already recorded, edited and produced.

But today, finally, the full course has been published on Pluralsight.

Entity Framework 6: Ninja Edition
– What’s New in EF6

It is a little over 7 hours long. This is what I would have done had I written another huge book. So if you are looking for my next book, just watch this course! And you can go back to it for reference.

If you don’t have a Pluralsight subscription (and honestly, the $29 monthly fee if you were to just subscribe to watch this course, is less than those huge books), send me a note and I’ll send you a code for a trial. You’ll probably realize quickly that you want a subscription though to continue accessing the enormous library.

Course Description

Entity Framework 6 brings major improvements to EF that allow developers to align their data access with advanced software practices. The biggest news for EF6 is that it is open-source and has gained a lot from developer community input. Features with broad appeal such as stored procedure mapping in code first, support for the Async/Await pattern when executing queries and commands, simpler patterns for unit testing, and built-in database logging capabilities have gotten a lot of visibility. EF6 is now very extensible with custom Migrations, custom mapping conventions, and the introduction of Dependency Injection patterns to open up low-level DbContext configuration. There are new methods and properties that allow simpler and smarter coding patterns. Rather than present a high level list of the new features, this course dives into each new feature in EF6, ensures that you understand not only what it is for, but how it works, scenarios where you can benefit from it, and gotchas you should watch out for. This course provides a comprehensive look at what EF6 adds to Entity Framework, and it will leave you with the ability to truly benefit from all of the Ninja power that’s been added to this version of EF.

Course Outline

Overview of What’s New in EF6

Introduction

What Is Entity Framework?

What’s in This Course?

What’s in This Module?

A Brief History of Entity Framework

Why EF6?

A Lap Around EF’s CodePlex Site

Overview of Changes to the EF Designer

Overview of New Features

What’s Not (Yet) in EF6

Summary

Resources

Getting to EF6

Introduction

In This Module

Getting EF6 Into New and Old Projects

Updating Projects to EF6

Summary

Resources

Performance and Stability Improvements

Introduction

In This Module

Faster Processing of LINQ’s Enumerable Contains

Faster Mapping View Generation

Using nGen to ‘Pre-JIT’ EF6 Assembly

Reuse Open Database Connections

Create DBs That Are More Scalable and Less Prone to Deadlocks

Connection Resiliency for Transient Database Connections

Digging into the Connection Resiliency Feature

Quick Review

Resources

Changes to the EF Tooling

Introduction

EF Designer History

In This Module

EF Designer’s New MSI Installer

Creating a Code First Model From a Database in the Designer

Database Views in Your Code First Model

Customizing the Code First Designer Templates

Refactoring the Generated POCOs and Model

A Warning About a Naming Conflict With Code First From Database

What Does the Empty Code First Model Wizard Do?

Comparing the Code First Model Wizard to the EF Power Tools

Using EF4 or EF5 With the New Designer

A Notable Change to the Model First Workflow

Why You Still Need the EF Power Tools

Quick Review

Resources

Stored Procedure Mappings for Code First

Introduction

In This Module

Understanding EF Stored Procedure Mappings

Visualizing Stored Procedure Mappings

Differences Between Designer-Based and Code First Model Mappings

Conventions for Procedures Created by Code First

Customizing Mappings to Work With Existing Stored Procedures

Quick Review

Resources

Custom Code First Conventions

Introduction

In This Module

Custom Code First Conventions: Why Would You Want Them?

Custom Conventions Basics With Lightweight Conventions

Using Attributes to Specify Custom Conventions

Encapsulating Custom Conventions

Understanding and Controlling Execution Order

Model-Based Conventions

Extending Existing Conventions

Quick Review

Resources

More Code First Goodies

Introduction

In This Module

Database Index Support in Code First

Adding Indexes With Fluent API

Setting the Default Database Schema

Using AddFromAssembly to Load Conventions and Configurations

Understanding and Fixing How Code First Pluralizes Table Names

Using a PluralizationService to Localize Non-English Table Names

Implementing a Custom Pluralization Rule in Your Data Layer

Mapping to Results of Table Value Functions and Stored Procedures

Quick Review

Resources

Enhancements to Code First Migrations

Introduction

In This Module

Affecting the Schema of the Migrations History Table

Smarter Migrations With Idempotent Scripts

Limitations of Existing Migrations Methods

How Migrations Get From Method to SQL

Create Custom Migrations for Other Database Operations

Why HasColumnAnnotation and HasTableAnnotation?

Implementing a Simple Table Annotation

Implementing More Complicated Annotations

Performance Tweak for MigrateDatabaseToLatestVersion Initializer

Migrate From Multiple Models to a Single Database

Using HasDefaultSchema and ContextKey for Multiple Model Support

Easier Migrations for Multiple Models in a Single Project

Combining Database Initializers and Migrations

Quick Review

Resources

Improved Database Interaction

Introduction

In This Module

Simple Database Logging With the Log Property

Tweaking the Log Functionality

SQLCE Functions for LINQ Queries

Introducing the Async EF6 Methods

Demonstrating the Effect of Asynchronous EF6 Methods

Perception and Performance: Load Testing With Async EF6

Quick Review

Resources

Code-Based DbContext Configurations and Interceptors

Introduction

Why DbConfiguration?

In This Module

Creating and Triggering a DbConfiguration Class

Why Move Config File Settings to Code?

Moving Connection Factory to DbConfiguration

Moving Database Initializers to DbConfiguration

The New NullDatabaseIntializer

Provider Services and DbConfiguration

Tap into the Pipeline With Interceptors

Beyond the Interceptor Basics

What Stops Does the DbCommandInterceptor Make in the Pipeline?

Building an Interceptor for Database Logging

Using Interceptors to Solve Complex Problems

Understanding the Role of Dependency Resolution

Hosting DbConfiguration in External Assemblies

Quick Review

Resources

Sometimes It’s the Little Things

Introduction

In This Module

EF6 and Mocking Frameworks

Writing Tests to Mock Methods Like DbSet.Find

Writing Tests to Mock LINQ Queries

Nested Entities and Complex Types

Fixing the Ambiguous Types Problem

Custom Equals vs. Change Tracker Equals

Smarter LINQ to Entities Queries

Yes, You Can Haz Changes With HasChanges

Quick Review

Resources