Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup Entity Framework / SQL Server with Mono

I'm trying to setup a very simple test project to evaluate Mono Entity Framework capabilities. When trying to access data, I get a runtime exception about parsing the model data when using .NET Runtime. When using Mono runtime, a stackoverflow exception is thrown.

This seems to be an internal mono bug which occurs when compiling the CSDL Schema Version 3 - see Mono Bugtracker.

So my question is:

How do I setup Mono with Entity Framework to work with a Microsoft SQL Server? Since I don't find much information, should this even be possible? Did anyone of you successfully setup a mono solution using EF and came across similar errors?

This is what I have done so far:

  • Installed Mono 3.0.1 Beta (latest stable doesn't include EntityFramework.dll)
  • Setup a Mono Profile for Visual Studio
  • Disabled strong name verification for delay signed assembilies for EntityFramework.dll / EntityFramework.SQLServer.dll and added them to the GAC to prevent runtime errors
  • Created a simple model + added Code Generation Items
  • written code using the model

The code works with Microsoft EntityFramework.dll (Version 6, Prerelease). When using the Mono equivalent, it looks like there are problems while parsing the entity model:

Exception message (.NET Runtime):

Object reference not set to an instance of an object.

Stacktrace (.NET Runtime):

   at System.Xml.XmlTextReaderImpl.InitStreamInput(Uri baseUri, String baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
   at System.Xml.XmlTextReaderImpl..ctor(String url, Stream input, XmlNameTable nt)
   at System.Xml.XmlTextReader..ctor(Stream input)
   at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
   at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
   at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.ComputeSchemaSet(SchemaDataModelOption dataModel)
   at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()
   at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)
   at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.GetSchemaSet(SchemaDataModelOption dataModel)
   at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.Parse(XmlReader sourceReader, String sourceLocation)
   at System.Data.Entity.Core.EntityModel.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths)
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.StoreMetadataEntry.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadItemCollection[T](IItemCollectionLoader`1 itemCollectionLoader, T entry)
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetOrCreateStoreAndMappingItemCollections(String cacheKey, MetadataArtifactLoader loader, EdmItemCollection edmItemCollection, Object& entryToken)
   at System.Data.Entity.Core.EntityClient.EntityConnection.LoadStoreItemCollections(MetadataWorkspace workspace, DbConnection storeConnection, DbConnectionOptions connectionOptions, EdmItemCollection edmItemCollection, MetadataArtifactLoader artifactLoader)
   at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
   at System.Data.Entity.Core.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure)
   at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
   at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
   at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Entity.Core.Objects.ObjectQuery`1.<GetEnumerator>m__2C3()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
   at EntityFrameworkMono.Program.Main(String[] args) in c:\Users\Christopher Dresel\Documents\Visual Studio 2012\Projects\New\EntityFrameworkMono\EntityFrameworkMono\Program.cs:line 17
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart() 

Exception message (Mono Runtime):

The requested operation caused a stack overflow.

Stacktrace (Mono Runtime):

  at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaElement.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaElement.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0 
  at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
...

This is the code I'm using:

CustomerEntities entities = new CustomerEntities();
var count = entities.Customers.Count(); // Exception throws here

Console.WriteLine(count);
Console.ReadKey();

EDMX file

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
    <!-- EF Runtime content -->
    <edmx:Runtime>
        <!-- SSDL content -->
        <edmx:StorageModels>
            <Schema Namespace="CustomerModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
                <EntityContainer Name="CustomerModelStoreContainer">
                    <EntitySet Name="Customer" EntityType="CustomerModel.Store.Customer" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
                </EntityContainer>
                <EntityType Name="Customer">
                    <Key>
                        <PropertyRef Name="CustomerID" />
                    </Key>
                    <Property Name="CustomerID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
                    <Property Name="CustomerName" Type="nvarchar" Nullable="false" MaxLength="50" />
                </EntityType>
            </Schema>
        </edmx:StorageModels>
        <!-- CSDL content -->
        <edmx:ConceptualModels>
            <Schema Namespace="CustomerModel" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns="http://schemas.microsoft.com/ado/2009/11/edm" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
                <EntityContainer Name="CustomerEntities" annotation:LazyLoadingEnabled="true">
                    <EntitySet Name="Customers" EntityType="CustomerModel.Customer" />
                </EntityContainer>
                <EntityType Name="Customer">
                    <Key>
                        <PropertyRef Name="CustomerID" />
                    </Key>
                    <Property Name="CustomerID" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
                    <Property Name="CustomerName" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" />
                </EntityType>
            </Schema>
        </edmx:ConceptualModels>
        <!-- C-S mapping content -->
        <edmx:Mappings>
            <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
                <EntityContainerMapping StorageEntityContainer="CustomerModelStoreContainer" CdmEntityContainer="CustomerEntities">
                    <EntitySetMapping Name="Customers">
                        <EntityTypeMapping TypeName="CustomerModel.Customer">
                            <MappingFragment StoreEntitySet="Customer">
                                <ScalarProperty Name="CustomerID" ColumnName="CustomerID" />
                                <ScalarProperty Name="CustomerName" ColumnName="CustomerName" />
                            </MappingFragment>
                        </EntityTypeMapping>
                    </EntitySetMapping>
                </EntityContainerMapping>
            </Mapping>
        </edmx:Mappings>
    </edmx:Runtime>
</edmx:Edmx>

And finally the connection string I'm using:

<connectionStrings>
    <add name="CustomerEntities"
         connectionString="metadata=.\CustomerModel.csdl|.\CustomerModel.ssdl|.\CustomerModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=CHRISTOPHERPC\SQLExpress;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient"/>
</connectionStrings>
like image 273
Dresel Avatar asked Nov 29 '12 10:11

Dresel


1 Answers

Dresel, misleading as my reputation may be on this site, I can safely say that using the EntityFramework with mono is not the recommended approach at this time. Although it is technically "supported", the majority of the library is non functional at best. After spending about a month digging as far as I could go, I was unable to peg the possibility of making a fully functioning site above %20. I instead used NHibernate and have been thrilled with the results. And recommend doing the same until the base has solidified further for the EF Mono project. Nhibernate Example (using MySQL, MSSQL supported)

I hope this helps at least a little bit as it's only my sincere thought. Good luck on whatever you choose to do, I know this MS Opensource move can get very "roadblocky"

like image 191
Chazt3n Avatar answered Sep 21 '22 00:09

Chazt3n