Using LightSwitch with EntityFramework 6 and CodeFirst based ODATA Controllers

Enhancing LightSwitch applications with additional ODATA or WebAPI controllers is a pretty common task. However when you try to build a CodeFirst based controller in combination with EntityFramework 6, you will run into a lot of errors by default. Here are the steps to get this cleared and running:

1. Create a Visual Studio LightSwitch HTML project
In this example we creatively named the project ‘LSEF01’.

2. Add a regular LightSwitch table in the internal ApplicationData database
The table is called ‘LsTable’ and has only a single additional property ‘Description’ which is optional.

3. Create a screen set for our LightSwitch table
Just create some simple screens (Browse, Add, Edit, View) in the HTMLClient project for the table ‘LsTable’ we just created to see if everything is working.
Running the application should now send you to the “BrowseLsTables” screen and let you add/edit entries in the ‘LsTables’ entity set.

4. Create a Model
Create a ‘Models’ folder in the Server project and create a new class file ‘EfClass.cs’ with this content:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LightSwitchApplication.Models
{
  public class EfClass
  {
    [Key]
    public int Id { get; set; }
    public string Description { get; set; }
  }
}

5. Build the project
This should still run fine as you have not actually put entity framework 6 into place.

6. Add EntityFramework 6
You can optionally specify a version number (currently EntityFramework is in version 6.1.1) and the project name. This is only needed if you already have added the DesktopClient which will not be compatible with the NuGet package.

Install-Package EntityFramework
Install-Package EntityFramework -Version 6.1.1
Install-Package EntityFramework -Version 6.1.1 -ProjectName LSEF01.Server

7. Add a Controller for our model
a) Create a ‘Controllers’ folder in the server project and create a Controller by using the scaffolder.
b) Choose the “Web API 2 OData Controller with actions, using Entity Framework” (right click the ‘Controllers’ folder, ‘Add’, ‘Controller…’, ‘Controller’, ‘Add’. Id: ‘ODataControllerWithContextScaffolder’)
c) Specify the following parameters:
‘Model class’: ‘EfClass (LightSwitchApplication.Models)’
‘Data context class’: ‘LightSwitchApplicationContext (LightSwitchApplication.Models)’
‘Use async controller actions’: true/checked
‘Controller name’: ‘EfClassesController^’

In case you cannot select the ‘Data context class’ you must add a new one with the ‘plus’ button. you can name it ‘LightSwitchApplication.Models.LightSwitchApplicationContext’. If this is not visible or possible or you get an error while adding the controller , make sure you have previously built the project at least once after adding the model.

8. Build the project and watch correct the errors
You should now get a bunch of errors like these here:

Error 11 The type or namespace name 'EdmEntityTypeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 104 6 <prj>.Server
Error 10 The type or namespace name 'EdmEntityTypeAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 104 6 <prj>.Server
Error 14 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 131 10 <prj>.Server
Error 16 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 158 10 <prj>.Server
Error 18 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 182 10 <prj>.Server
Error 20 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 206 10 <prj>.Server
Error 22 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 230 10 <prj>.Server
Error 24 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 254 10 <prj>.Server
Error 26 The type or namespace name 'EdmScalarPropertyAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 278 10 <prj>.Server
Error 13 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 131 10 <prj>.Server
Error 15 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 158 10 <prj>.Server
Error 17 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 182 10 <prj>.Server
Error 19 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 206 10 <prj>.Server
Error 21 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 230 10 <prj>.Server
Error 23 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 254 10 <prj>.Server
Error 25 The type or namespace name 'EdmScalarPropertyAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 278 10 <prj>.Server
Error 5 The type or namespace name 'EdmSchemaAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 19 12 <prj>.Server
Error 4 The type or namespace name 'EdmSchemaAttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 19 12 <prj>.Server
Error 1 The type or namespace name 'EntityClient' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 12 19 <prj>.Server
Error 7 The type or namespace name 'EntityConnection' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 50 32 <prj>.Server
Error 12 The type or namespace name 'EntityObject' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 107 36 <prj>.Server
Error 6 The type or namespace name 'ObjectContext' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 27 44 <prj>.Server
Error 2 The type or namespace name 'Objects' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 13 19 <prj>.Server
Error 3 The type or namespace name 'Objects' does not exist in the namespace 'System.Data' (are you missing an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 14 19 <prj>.Server
Error 8 The type or namespace name 'ObjectSet' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 68 16 <prj>.Server
Error 9 The type or namespace name 'ObjectSet' could not be found (are you missing a using directive or an assembly reference?) <prj>\GeneratedArtifacts\ApplicationDataObjectContext.cs 79 17 <prj>.Server

a) Add System.Data.Entity reference
Add the ‘System.Data.Entity’ reference from the installed .NET Framework assemblies (Menu ‘Project’, ‘Add Reference’, Assemblies’, ‘Framework’, search for ‘System.Data.Entity’. This should be the default version 4 that ships with .NET Framework v4.

b) Resolve ambiguous ‘EntityState’ reference

Error 1 'EntityState' is an ambiguous reference between 'System.Data.Entity.EntityState' and 'System.Data.EntityState' <prj>.Server\Controllers\EfClassesController.cs 58 39 LSEF01.Server

The scaffolder created action that use the ‘EntityState’ class that has been refactored due to the open source release of EntityFramework. You have to fully qualify the class:

// ambiguous / error:
db.Entry(efClass).State = EntityState.Modified;
// change to:
db.Entry(efClass).State = System.Data.Entity.EntityState.Modified;

You can also check Update namespaces for any core EF types being used for further explanation on this.

c) Install NuGet package for OData
You have to add the OData NuGet package Microsoft ASP.NET Web API 2.2 for OData v1-3:

Install-Package Microsoft.AspNet.WebApi.OData -ProjectName LSEF01.Server

Again you only have to specify the project name if you have other projects in the solution that are not compatible with it (i.e. the Silverlight Deskto client).

d) Edit WebApiConfig to add OData router and controller
Add usings and OData route information and register the entity set ‘EfClasses’ for our ‘EfClass’ model. the resulting ‘WebApiConfig.cs’ might end up looking like this:

using System;
using Microsoft.Data.Edm;
using System.Diagnostics;
using System.Web.Http;
// using System.Web.Http.OData;
using System.Web.Http.OData.Batch;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
// using System.Web.Http.OData.Query;
// using System.Web.Http.OData.Routing;
// using System.Web.Http.OData.Extensions;

namespace LightSwitchApplication
{
  public static class WebApiConfig
  {
    public static void Register(HttpConfiguration config)
    {
      config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
      );
      config.Routes.MapODataServiceRoute(
        routeName: "Utilities.svc"
        ,
        routePrefix: "Utilities.svc"
        ,
        model: GetModel("Utilities")
        ,
        batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer)
        );
      config.MapHttpAttributeRoutes();
      //config.EnableQuerySupport();
    }
    private static IEdmModel GetModel(string ContainerName)
    {
      ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
      builder.ContainerName = ContainerName;
      builder.EntitySet<LightSwitchApplication.Models.EfClass>("EfClasses");

      return builder.GetEdmModel();
    }
  }
}

Enabling batch support is certainly optional and has nothing to do with our example here, but is useful anyway. ‘EnableQuerySupport’ would be better activated in the controller for each action that really needs to support it.

9. Re-Build the project
All errors should now be fixed and the project should build successfully.

10. Enable database support
a) Enabling database support should result in message similar to this:

Enable-Migrations -ContextProjectName 'LSEF01.Server' -StartupProjectName 'LSEF01.Server' -Force

Checking if the context targets an existing database...
Code First Migrations enabled for project LSEF01.Server.

b) Add your initial migration:

Add-Migration Initial -ProjectName 'LSEF01.Server' -StartupProjectName 'LSEF01.Server' -Force

Scaffolding migration 'Initial'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Initial' again.

c) Now run your application and try to perform CRUD operations with your ‘EfClasses’ controller
Use Telerik Fiddler or anything else to get these requests to the server:

// request
GET http://server1/Utilities.svc/EfClasses HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US

// response
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
DataServiceVersion: 3.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:14:01 GMT
Content-Length: 104

{
  "odata.metadata":"http://server1/Utilities.svc/$metadata#EfClasses"
  ,
  "value":[  ]
}
// request
POST http://server1/Utilities.svc/EfClasses HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US
Content-Length: 31
Content-Type: application/json

{"Description":"myDescription"}

// response
HTTP/1.1 201 Created
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Location: http://server1/Utilities.svc/EfClasses(1)
Server: Microsoft-IIS/8.0
DataServiceVersion: 3.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:17:10 GMT
Content-Length: 129

{
  "odata.metadata":"http://server1/Utilities.svc/$metadata#EfClasses/@Element"
  ,
  "Id":1
  ,
  "Description":"myDescription"
}
// request
PUT http://server1/Utilities.svc/EfClasses(1) HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US
Content-Length: 39
Content-Type: application/json

{"Description":"myDescription2","Id":1}

// response
HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:21:42 GMT
// request
PATCH http://server1/Utilities.svc/EfClasses(1) HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US
Content-Length: 32
Content-Type: application/json

{"Description":"myDescription20000"}

// response
HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:23:22 GMT
// request
GET http://server1/Utilities.svc/EfClasses(1) HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US

// response
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
DataServiceVersion: 3.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:17:17 GMT
Content-Length: 129

{
  "odata.metadata":"http://server1/Utilities.svc/$metadata#EfClasses/@Element"
  ,
  "Id":1
  ,
  "Description":"myDescription"
}
// request
DELETE http://server1/Utilities.svc/EfClasses(1) HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US

// response
HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:19:37 GMT

[Optional] 11. Correct missing database path
In case you got an HTTP 500 with an error message like below you have to adjust the database path where EntityFramework searches for your database. I am actually not sure why this happens, and this might be fixed in a more elegant way. But this here works as well by using Windows Sysinternals – Junction.

C:\> junction.exe W:\prj\LSEF01\LSEF01\LSEF01.Server\App_Data W:\prj\LSEF01\LSEF01\bin\Debug\App_Data
GET http://server1/Utilities.svc/EfClasses HTTP/1.1
MaxDataServiceVersion: 3.0
Accept: application/xml
Referer: http://server1/HTMLClient/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Host: server1
Cookie: msls-client-parameters=preferredLanguage=en-US


HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/8.0
DataServiceVersion: 3.0
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
X-Powered-By: ASP.NET
Date: Sun, 09 Nov 2014 10:09:39 GMT
Content-Length: 7032

<?xml version="1.0" encoding="utf-8"?>
<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <m:code />
  <m:message xml:lang="en-US">An error has occurred.</m:message>
  <m:innererror>
    <m:message>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'.</m:message>
    <m:type>System.InvalidOperationException</m:type>
    <m:stacktrace></m:stacktrace>
    <m:internalexception>
      <m:message>Directory lookup for the file "W:\prj\LSEF01\LSEF01\bin\Debug\App_Data\LightSwitchApplicationContext-20141108164316.mdf" failed with the operating system error 2(The system cannot find the file specified.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.</m:message>
      <m:type>System.Data.SqlClient.SqlException</m:type>
      <m:stacktrace>   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean&amp; dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass1a.<CreateDatabaseFromScript>b__19(DbConnection conn)
   at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)
   at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
   at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
   at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
   at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
   at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
   at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update()
   at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
   at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
   at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
   at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
   at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
   at System.Data.Entity.Internal.InternalContext.Initialize()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator()
   at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer, ODataSerializerContext writeContext)
   at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
   at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
   at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)
   at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()</m:stacktrace>
    </m:internalexception>
  </m:innererror>
</m:error>

12. Change model and update database schema
Now whenever you change any of your models all you have to do is add a migration and update the database from that:

Add-Migration -StartupProjectName 'LSEF01.Server‘ -Name Initial
Update-Database -ProjectName 'LSEF01.Server' -StartupProjectName 'LSEF01.Server'

This is a basically all it takes to convince LightSwitch and EF 6 to play nicely together. For more details on how to use EF6 with WebAPI you should have a look at this series of articles: Using Web API 2 with Entity Framework 6. Have fun!

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

%d bloggers like this: