Category Archives: Data Access

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

EF7 EnsureCreated vs. Migrate Methods

I had a “demo gods” problem recently…of course I hit the jackpot combo during a conference presentation though never while practicing.

Remember that EF7 is not EF6 with new features. So behavior can change and I didn’t check this one.

In EF6 if you have migrations and either let DbInitialization create the database or use Database.Create(), the database will get created along with the migrations in the MigrationHistory table.

With EF7 if you use EnsureCreated to create the database at runtime, as I had in some of my tests where I literally wanted to check behavior in the database, the migration history table DOES NOT GET CREATED.

This messed me up because I was demoing a migrations feature after having run one of these tests. With the migration history table wiped out by my test, the update-database command attempted to start with the very first migration, not the one I had just added in my demo. This caused a conflict because that migration was attempting to create a table that already existed in the database.

I couldn’t figure out what the problem was on the fly, so I moved on, with assurances to the attendees that I’d done a lot of work with migrations and new they worked as expected. And that a) it was a beta b) I would run it by the team and c) “you can trust me”.

So, blaming it on “beta” was not fair and it was not right. The blame lay between the chair and the keyboard, as they say. I hadn’t even run that test in my conference session yet.  But I had re-run all fo the tests one last time right before I started the session, which put the database in this bad state.

Here, from one of EF7 issues raised on Github is Rowan Miller’s explanation:

EnsureCreated totally bypasses migrations and just creates the schema for you, you can’t mix this with migrations. EnsureCreated is designed for testing or rapid prototyping where you are ok with dropping and re-creating the database each time. If you are using migrations and want to have them automatically applied on app start, then you can use context.Database.Migrate() instead.

So I’ve gone back to my tests and made sure the ones that use the database make use of the Migrate command.

My anticipated uses:

  • EnsureCreated for on the fly DB creation on devices (e.g. phones)
  • EnsureCreated for integration testing when I’m pointing to a unique testing-only database.
  • Migrate for integration testing when my tests involve a test database that uses migrations. I think this will be rare and this is what I wanted for my conference demo.
  • Migrate for, as Rowan suggests, Migrating a db on app startup. This could be for example, client apps (ala WPF) or web sites you’ve deployed to Azure.

Keep in mind that these demos where Migrate made more sense, are demos I am using to help people understand how EF7 works, not to demonstrate how to build tests when employing Entity Framework in your application. So some of the things I am doing are not necessarily how I would use tests when building software.

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.

Installing EF Power Tools into VS2015 (with an update for VS2019)

March 2020: In comments below, someone asked about VS2019.

The EF Power Tools Community Edition (see July 2017 note below) still works for VS2019.

Erik EJ also created EF Core Power Tools.

While I’m at it, I thought I would also point out the plain old EF Tools for VS2019. For VS2019 (& IIRC for VS2017), these tools are installed via the Visual Studio Installer.
Entity Framework tools are installed as part of the Data storage and processing workload in the Visual Studio Installer.

You can also install them as an individual component under the SDKs, libraries, and frameworks category.

July 2017: something amazing happened! Erik Ejlskov Jensen, the creator of the SQLCe provider Entity Frameworkas well as the creator of the very popular SQL Server Compact Toolbox extension for Visual Studio, has given us a community version of EF Power Tools for VS2015 and VS2017. Thanks to the tools already being on GitHub, he forked the tools and now we have

EF6 Power Tools Community Edition that you can get via Visual Studio Extensions

Oct 2016 note: There have been over 60,000 hits to this blog post so far. My host is reaping the benefits ($$$). In July, I submitted a pull request to update the VSIX. The PR was finally merged. Now just waiting for the change to show up in the VS Gallery.

TLDR: If you don’t want to do the tasks (even though they are so easy) you can download the updated VSIX I created from here.

The Entity Framework Power Tools extension for Visual Studio has been around for quite some time and is still called a Beta. I cannot live without it’s “View Entity Data Model (Read-Only)” feature which I used to validate my code first models.

But if you try to install the extension into Visual Studio 2015, you won’t find it.

7-25-2015 9-47-12 AM

Checking the extension in Visual Studio Gallery, you’ll see that it hasn’t been updated to install into VS2015.7-25-2015 9-47-49 AM

The fix is nothing more than making it know about VS2015. There are no other compatibility problems that I have experienced. Modifying an extensions installation package (which is just a zip file!) to be aware of another version of Visual Studio is pretty easy. Here are the steps to get the EF Power Tools into VS2015.

Download the extension from the Visual Studio Gallery page.

Find the file

7-25-2015 9-50-13 AM

and change it’s extension to zip.

7-25-2015 9-50-33 AM

Extract the files from the zip file.

7-25-2015 9-53-01 AM

Open the extension.vsixmanifest file in a text editor and find the Supported Products section.

7-25-2015 9-53-25 AM

And copy paste one of the Visual studio elements, changing the version to 14.0. I have the Enterprise version but didn’t bother changing it from Pro here and it didn’t seem to be a problem.

7-25-2015 9-53-47 AM

Now you have to reverse your steps in order to recreate the VSIX file.

Select the files in the extracted folder and zip them. Don’t zip the folder. The files have to be at the root. (Guess how I learned that! Smile ) I named my zip file VSPowerTools15.zip

7-25-2015-9-55-47-AM.png

Rename the file to have the vsix extension.

7-25-2015 9-56-01 AM

Run the file right from here.

7-25-2015 9-56-16 AM

Voila!

7-25-2015 9-56-22 AM

If Visual Studio was open, you’ll have to restart to get this to kick in.

Also you’ll see Entity Framework Power Tools listed in the installed extensions when you look at the About section of Visual Studio 2015.

I accidentally mistook this for something it was NOT and (embarrassingly) tweeted it. I had forgotten that I had done this for the VS2015 preview. Then I installed VS2015 RTM on top of the preview and that picked up all of the installed extensions. When I saw the power tools listed in About, I thought they had a) finally gotten rid of the “Beta” tag and b) installed automatically with VS2015. When I realized the extension was installed, I uninstalled that and indeed the tool went away. So for anyone who saw that tweet…. sorry! Guilty as charged …

EF7 Beta 4 & LINQ Queries: Be sure you have the right LINQ package

TLDR:
For EF7 Beta 4 (via nuget) the package you want is Remotion.Linq 2.0.0-alpha-002.

I recently updated some demos from using the EF7 stable (stable comes from Nuget.org, not the nightly build package source) version beta3 to beta4. It involved updating a lot of other packages and I know enough to be dangerous so this took me a while.

But I got it worked out and everything compiled and everything ran correctly …or so I thought.

There was a test I missed running which performed some LINQ queries.

I tried to demo that at in a conference session earlier this week at Techorama and it threw an exception. Rather than struggling with it, I assured the attendees that I knew this worked and was probably a versioning issue. I finally got a chance to dig into that today and have solved the problem.

It was indeed a version issue. I found a GitHub issue that indicated this problem was caused by having the wrong version of Remotion.Linq installed. But the conversation was based on an earlier build of EF7 and wasn’t sure which version of Remotion.Linq.

But in fixing the problem, I targeted the wrong version for an update, thinking the “stable” build might be what I wanted since the EF7 betas in nuget are considered “stable” betas. Unfortunately trying to install that stable version (1.15.15) caused nuget to hang for so long I had to just crash visual studio. I tried this repeatedly from different angles so I wasted over an hour being a dummy.

When I finally decided to try the 2.0.0-alpha-002 installed, it updated quickly and easily and my LINQ queries executed successfully.

Some EF7 Beta3 to Beta4 API Syntax Changes

I am updating some demos I created earlier in the year and using the Beta4 version of EF7 that is the latest stable beta and available on Nuget as opposed to the super-bleeding edge APIs you can get via the nightly builds source.

There were some API changes to features I was using and I had to do a bit of exploring to sort them out so wanted to share in case you are doing the same.

Keep in mind that there are a LOT of things that have evolved between these two versions. I’m just focusing on the things I had to change so that my little demos continued to work properly. Smile

AttachGraph

DbContext.ChangeTracker.AttachGraph is now DbContext.ChangeTracker.TrackGraph.

Here’s an example of it in use with a graph of all new objects and the root of the graph is newSamurai.

context.ChangeTracker.TrackGraph(newSamurai,

e => e.State=EntityState.Added);

DbContextOptions

DbContextOptions is now DbContextOptionsBuilder.

You’ve most likely seen this used as a parameter in the OnConfiguring override for DbContext.

Here is the original signature:

protected override void OnConfiguring(DbContextOptions options) {}

Here is the new signature:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }

DbContext/DbSet.Add Overload for Ranges

EF6 has DbSet.AddRange. Originally EF7 switched the functionality to be an overload of Add which was cool but not backwards compatible so we’re back to DbContext.AddRange and DbSet.AddRange.

DbContext.Entry.SetState( )

The DbContext ChangeTracker API since EF4.1 let us set state with

DbContext.Entry.State= EntityState (where EntityState is an enum)

EF7 started out with a nicer API for this which was

DbContext.Entry.SetState(EntityState)

But for the sake of backwards compatibility, it’s now back to

DbContext.Entry.State=EntityState

 

That’s what I’ve encountered so far. Hope it helps

Looking Ahead to Entity Framework 7 on Pluralsight

Pluralsight has published my latest course, a 2.5 hour course about Entity Framework 7 (EF7).

“Looking Ahead to Entity Framework 7”

EF7 is not released yet. It will get released as a “pre-release” along with ASP.NET 5 so that there is a data stack available for projects that target the CoreCLR. Then the team will do a lot more work on EF7 for a full release possibly (wild guess) at the end of 2015. There are a lot of changes since EF7 is begin rewritten from the ground up. Many new features – from things like Batch Updates that we’ve been asking for since v1 to totally new concepts like being able to query and update against non-relational data stores. But there will also be things that do not get carried forward – most notably for some is the EDMX, the designer based entity model.

This course will show you what’s coming, what’s going, demonstrate a lot of the new features (as they are currently …aka the Alpha or earlier versions) and provide guidance about deciding if and when to move to EF7.

Here is an list of the modules:

You can see the more detailed Table of Contents here.

I’ve already gotten some great feedback on the course. My favorite tweet so far was:

“Great info and insight. I don’t know if I’m happier with what’s being added or being removed.”

Check it out and let me know what you think of EF7!

Some Observations While Playing With EF7 Alpha Bits: Current vs On-Hold APIs

You may or may not have caught this important blog post from the EF team about plans for the first RTM of EF7:  EF7 – Priorities, Focus, and Initial Release. In it, EF Program Manager, Rowan Miller explains that for its initial release, EF7 will target ASP.NET 5, ensuring that ASP.NET 5 has a solid data platform to release with. It also means setting aside some of the proof of concept work that the team has been working on for it’s “new platforms, new data stores” initiative. Namely, Windows Store &  Windows Phone and the non-relational providers that the team has been experimenting with are on hold until after the initial RTM of EF7. This does *not* mean that they are being dropped, just delayed so that the team can focus on shipping something usable sooner. Rowan is also clear about the fact that EF7 will not be considered the “go-to” EF version until much later when they’ve brought these other features in as well as forged ahead with more parity with EF6. I recommend that you read that post.

So what does that mean with respect to the source code for EF7 on Github and the current preview Nuget packages of EF?

Note that I have a package source that is pointed to the ASPNET vNext packages which is also where EF7 lives on myget: https://www.myget.org/F/aspnetvnext/api/v2

Also that I have selected PRERELEASE packages:

image

And using the console, that means always adding the “-pre” parameter after the install-package command (e.g. install-package entityframework –pre).

First, here’s a look at what DLLs were on Nuget prior to the shift

image

The shift occurred when the nuget packages went from being tagged as alpha to being tagged as RC. Note that these nuget tags do not reflect the state of EF7, but a package naming decision.

image

Notice that the AzureTableStorage, Redis and SQLite packages are still there but they are from Dec 1, 2014.

Notice the addition of EntityFramework.Core. That’s where all of the core bits are now.  But the entityframework package is still there. You still start by installing entityframework.

The entityframework package has a dependency on entityframework commands and will pull that in and then that forces nuget to also pull in entityframework.core, relational and migrations. You’ll need to explicitly install entityframework.SqlServer or InMemory if you want them. You’ll need at least one of those.

When you install EF7 from the ASPNetVNext package source, when the installation is finished the following HTML page will pop up in Visual Studio:

image

I have not tried to use the older providers. They are not going to be kept in sync with the moving forward packages. They will get caught up after EF7 has its initial release.

Also, you do have the ability to get at the source code as it was prior to this big shift. Check the “futures” branch on github:

https://github.com/aspnet/EntityFramework/tree/futures

I believe this is a snapshot that was taken prior to the shift.

Unfortunately, it’s not possible to keep all previous versions of packages on MyGet the way it is on Nuget.  You can get a snapshot of the beta2.11514 packages that Rowan Miller set aside for his Connect demos. https://github.com/rowanmiller/Demo-EF7/  That’s not the latest version of EF7 prior to the shift but close.

Just remember, it is all still early early, evolving and changing rapidly.

Some Observations While Playing With EF7 Alpha Bits: EF7-Able Projects

You can’t install EF7 into just any project. Especially now that they are making the shift to focusing on ASP.NET 5 for it’s initial release.

Here are combinations that will work:

(Have not tried VS2012 ..)

Visual Studio 2013

.NET 4.5.1 projects only

Class Library, Client Projects (WPF, Console, Windows Forms), ASP.NET Projects, WCF

Later in 2015, EF7 will return to working with Windows Phone/Store, but for now, none of the relevant projects will host EF7 (e.g. universal apps, PCLs, etc)

Visual Studio 2015

.NET 4.5.1+ projects only

Class Library, Client Projects (WPF, Console, Windows Forms), ASP.NET Projects, WCF

ASP.NET 5 vNext Console & Class Library projects (and yes, the first sounds like an oxymoron)

image

ASP.NET apps (and if you’re looking for vNext, those are in the templates)

image