首先使用实体​​框架代码映射SqlGeography [英] Mapping SqlGeography using Entity Framework code first

查看:108
本文介绍了首先使用实体​​框架代码映射SqlGeography的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩实体框架4和 sqlgeography 数据类型。我无法使Entity Framework将我的sqlgeography类型映射到数据库。我已将我的课程定义为POCO,并希望实体框架为我创建表。我没有成功,然后尝试自己创建表,没有成功。



我的课程看起来像这样:

  using System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用Microsoft.SqlServer.Server;
使用Microsoft.SqlServer.Types;

命名空间Nearest.Models
{
public class Point
{
public int Id {get;组; }
public int DataSet {get;组; }
public int作者{get;组; }
public SqlGeography Geo {get;组; }
public string Data {get;组; }
}
}

这是我得到的错误: p>

 <异常xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns:xsd = http://www.w3.org/2001/XMLSchema\"> 
< ExceptionType> System.InvalidOperationException< / ExceptionType>
< Message>
尝试创建类型为Nearest.Controllers.PointsController的控制器时发生错误。确保控制器具有无参数的公共构造函数。
< / Message>
< StackTrace> System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext controllerContext,类型controllerType)在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext controllerContext,Type controllerType)在System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateInstance(HttpControllerContext controllerContext,HttpControllerDescriptor controllerDescriptor)在$ System.Web.Http.Dispatcher System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancelToken)中的System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage请求,CancellationToken cancelToken)上的.DefaultHttpControllerFactory.CreateController(HttpControllerContext controllerContext,String controllerName)
< / StackTrace>
< InnerException>
< ExceptionType> System.TypeInitializationException< / ExceptionType>
< Message>
'Nearest.Controllers.PointsController'的类型初始化器抛出异常。
< / Message>
< StackTrace>
在Nearest.Controllers.PointsController..ctor()在lambda.method(Closure)在System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext controllerContext,类型controllerType)
< / StackTrace>
< InnerException>
< ExceptionType> System.Data.DataException< / ExceptionType>
< Message>
初始化数据库时发生异常。有关详细信息,请参阅InnerException。
< / Message>
< StackTrace> System.Data.Entity.Internal.LazyInternalContext。System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)中的
。System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()在System.Data.Entity.Internal.LazyInternalContext。< InitializeDatabase> b__4 (System.Data.Entity.Internal.RetryAction)中的System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput输入)在System.Data.Entity.Internal.LazyInternalContext的System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1动作)(InternalContext c) System.Data.Entity.Internal.Linq.InternalSet中的System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)的.InitializeDatabase()在System.Data.Entity.Internal.Linq.InternalSet `1.GetEnumerator()在System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable< TResult> .GetEnumerator()在System.Linq.Enumerable.Count [TSource](IEnumerable`1源)在C:\Projects\Nearest\tru中的Nearest.Models.PointRepository..ctor() nk\Nearest\Models\PointRepository.cs:第15行在C:\Projects\Nearest\trunk\Nearest\Controllers\PointsController.cs中的Nearest.Controllers.PointsController..cctor()第14行
< / StackTrace>
< InnerException>
< ExceptionType> System.Data.EntityCommandCompilationException< / ExceptionType>
< Message>
准备命令定义时发生错误。查看内部例外情况。
< / Message>
< StackTrace> System.Data.EntityClient.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory,DbCommandTree commandTree)在System.Data.EntityClient.EntityProviderServices.CreateCommandDefinition(DbProviderFactory storeProviderFactory,DbCommandTree commandTree)在System.Data.EntityClient.EntityProviderServices.CreateDbCommandDefinition(
)在System.Data.Objects.Internal.ObjectQueryExecutionPlan.Prepare(ObjectContext context,DbQueryCommandTree tree,Type elementType,MergeOption mergeOption,Span span,ReadOnlyCollection)中的System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)上的DbProviderManifest providerManifest,DbCommandTree commandTree) 1)在System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption),在System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)在System.Data.Objects.ObjectQuery`1的编译QueryParameters)。 System.Collections.Generic.IEnumerable< T> .GetEnumerator()在System.Linq.En在System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle []中的System.Data.Objects.ELinq.ObjectQueryProvider。< GetElementFunction> b__1 [TResult](IEnumerable`1序列)中的umerable.FirstOrDefault [TSource](IEnumerable`1 source)在System.Data.Entity.Internal.Linq.DbQueryProvider.Execute中的System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute [S](表达式表达式)中的一个查询(表达式查询)在System.Linq.Queryable.FirstOrDefault [System.Data.Entity.Internal.InternalContext.CompatibleWithModel上的System.Data.Entity.Internal.InternalContext.QueryForModelHash()的System.Linq.Queryable.FirstOrDefault [Iourceable] 1源代码(表达式表达式) (System.Data.Entity.CreateDatabaseIfNotExists)上的(Boolean throwIfNoMetadata)System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)在System.Data.Entity.Internal.InternalContext。  c__DisplayClass5。  PerformDatabaseInitialization> b__3()在System.Data.Entity .Internal.InternalContext.PerformInitializationAction(动作action)
< / StackTrace>
< InnerException>
< ExceptionType> System.Data.MappingException< / ExceptionType>
< Message>
(6,10):错误3004:映射从第6行开始的片段的问题:没有为SetPoint中的属性Point.Geo指定映射。当实体类型为[Nearest.Models.Point]
< / Message>时,具有密钥(PK)的实体将不会往返
< StackTrace>在System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainer容器,Dictionary`2 resultDictionary)在System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer容器)在System.Data.Common.Utils的
。 Memoizer`2 .c__DisplayClass2。< Evaluate> b__0()在System.Data.Common.Utils.Memoizer`2.Result.GetValue()在System.Data.Common.Utils.Memoizer`2.Evaluate(在System.Data.QueryPlayCompiler上的System.Data.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase扩展名)上的System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent,MetadataWorkspace workspace,StorageMappingItemCollection storageMappingItemCollection)。 System.Data.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode,ScanTableOp scanTableOp,IsOfOp& type)中的PreProcessor.ExpandView(Node node,ScanTableOp scanTableOp,IsOfOp& typeFilter)过滤)System.Data.Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op,Node n)在System.Data.Query.InternalTrees.ScanTableOp.Accept System.Data中的[TResultType](BasicOpVisitorOfT`1 v,Node n)。 System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op,Node n)在System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)处的Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n) System.Data.Query.InternalTrees中的System.Data.Query.InternalTrees.ProjectOp.Accept [TResultType](BasicOpVisitorOfT`1 v,Node n)的.Data.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op,Node n)。 System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)的System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op,Node n)在System.Data.Query中的BasicOpVisitorOfT`1.VisitNode(Node n) .PlanCompiler.PreProcessor.Visit(ProjectOp op,Node n)在System.Data.Query.InternalTrees.ProjectOp.Accept [TResultType](BasicOpVisit orOfT`1 v,Node n)在System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)在System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)在System.Data.Query.PlanCompiler在System.Data.Query.InternalTrees.BasicOpVisitorOfT中,System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitSortOp(SortBaseOp op,Node n)上的.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op,Node n).Visit(ConstrainedSortOp op, System.Data.Query.InternalTrees.ConstrainedSortOp.Accept [TResultType](BasicOpVisitorOfT`1 v,Node n)在System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)在System.Data处的节点n)。 System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op,Node n)在System.Data上的System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)上的Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) .Query.InternalTrees.BasicOpVisitorOfT`1.Visit(PhysicalProjectOp op,Node n)在System.Data.Query.Inter NalTrees.PhysicalProjectOp.Accept System.Data.Query.PlanCompiler.PreProcessor.Process()中的System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)的[TResultType](BasicOpVisitorOfT`1 v,Node n) System.Data.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState,StructuredTypeInfo&在System.Data.EntityClient.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory)上的System.Data.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands,ColumnMap& resultColumnMap,Int32& ColumnCount,Set`1& entitySets)中的typeInfo) DbCommandTree commandTree)
< / StackTrace>
< / InnerException>
< / InnerException>
< / InnerException>
< / InnerException>
< / Exception>


解决方案

据我所知,EF4尚未支持SQL Server 2008的 Geography Geometry 数据类型。这将是Entity Framework v5的一个功能 - 今年晚些时候发布了.NET 4.5)。



查看 EF5空间类型演练,以说明EF5如何支持空间类型。



请参阅这个博客由EF女神朱莉·莱曼关于如何仍然使用地理类型与EF4 - 有一点额外的工作 - 不知道有多少工作在EF代码优先,虽然。



另外:查看此主题的其他SO文章


I am playing around with Entity Framework 4 and the sqlgeography datatype. I am having trouble getting Entity Framework map my sqlgeography types to the db. I have defined my class as POCO and would like entity framework to create the tables for me. I didn't succeed in this and have then tried creating the table myself without success either.

My class looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Types;

namespace Nearest.Models
{
    public class Point
    {
        public int Id { get; set; }
        public int DataSet { get; set; }
        public int Author { get; set; }
        public SqlGeography Geo { get; set; }
        public string Data { get; set; }
    }
}

and this is the error I get:

<Exception xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ExceptionType>System.InvalidOperationException</ExceptionType>
<Message>
An error occurred when trying to create a controller of type 'Nearest.Controllers.PointsController'. Make sure that the controller has a parameterless public constructor.
</Message>
<StackTrace>
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext controllerContext, Type controllerType) at System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateInstance(HttpControllerContext controllerContext, HttpControllerDescriptor controllerDescriptor) at System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateController(HttpControllerContext controllerContext, String controllerName) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
</StackTrace>
<InnerException>
<ExceptionType>System.TypeInitializationException</ExceptionType>
<Message>
The type initializer for 'Nearest.Controllers.PointsController' threw an exception.
</Message>
<StackTrace>
at Nearest.Controllers.PointsController..ctor() at lambda_method(Closure ) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext controllerContext, Type controllerType)
</StackTrace>
<InnerException>
<ExceptionType>System.Data.DataException</ExceptionType>
<Message>
An exception occurred while initializing the database. See the InnerException for details.
</Message>
<StackTrace>
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.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.Generic.IEnumerable<TResult>.GetEnumerator() at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source) at Nearest.Models.PointRepository..ctor() in C:\Projects\Nearest\trunk\Nearest\Models\PointRepository.cs:line 15 at Nearest.Controllers.PointsController..cctor() in C:\Projects\Nearest\trunk\Nearest\Controllers\PointsController.cs:line 14
</StackTrace>
<InnerException>
<ExceptionType>System.Data.EntityCommandCompilationException</ExceptionType>
<Message>
An error occurred while preparing the command definition. See the inner exception for details.
</Message>
<StackTrace>
at System.Data.EntityClient.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree) at System.Data.EntityClient.EntityProviderServices.CreateCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree) at System.Data.EntityClient.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree) at System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree) at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Span span, ReadOnlyCollection`1 compiledQueryParameters) at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source) at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence) at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot) at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source) at System.Data.Entity.Internal.InternalContext.QueryForModelHash() at System.Data.Entity.Internal.InternalContext.CompatibleWithModel(Boolean throwIfNoMetadata) at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass5.<PerformDatabaseInitialization>b__3() at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
</StackTrace>
<InnerException>
<ExceptionType>System.Data.MappingException</ExceptionType>
<Message>
(6,10) : error 3004: Problem in mapping fragments starting at line 6:No mapping specified for properties Point.Geo in Set Points. An Entity with Key (PK) will not round-trip when: Entity is type [Nearest.Models.Point]
</Message>
<StackTrace>
at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainer container, Dictionary`2 resultDictionary) at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer container) at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0() at System.Data.Common.Utils.Memoizer`2.Result.GetValue() at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg) at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection) at System.Data.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase extent) at System.Data.Query.PlanCompiler.PreProcessor.ExpandView(Node node, ScanTableOp scanTableOp, IsOfOp& typeFilter) at System.Data.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode, ScanTableOp scanTableOp, IsOfOp& typeFilter) at System.Data.Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op, Node n) at System.Data.Query.InternalTrees.ScanTableOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n) at System.Data.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n) at System.Data.Query.InternalTrees.ProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n) at System.Data.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n) at System.Data.Query.InternalTrees.ProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitSortOp(SortBaseOp op, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.Visit(ConstrainedSortOp op, Node n) at System.Data.Query.InternalTrees.ConstrainedSortOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n) at System.Data.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.Visit(PhysicalProjectOp op, Node n) at System.Data.Query.InternalTrees.PhysicalProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n) at System.Data.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n) at System.Data.Query.PlanCompiler.PreProcessor.Process() at System.Data.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState, StructuredTypeInfo& typeInfo) at System.Data.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets) at System.Data.EntityClient.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree)
</StackTrace>
</InnerException>
</InnerException>
</InnerException>
</InnerException>
</Exception>

解决方案

As far as I know, EF4 doesn't yet support the Geography and Geometry datatypes of SQL Server 2008. This will be a feature of Entity Framework v5 -- to be released with .NET 4.5 later this year).

See a EF5 Spatial Types Walkthrough for an explanation of how EF5 will support spatial types.

And see this blog post by EF goddess Julie Lerman on how to still use geography types with EF4 - with a bit of extra work - not sure how much of that works in EF code-first, though.

Also: see this other SO post on the topic

这篇关于首先使用实体​​框架代码映射SqlGeography的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆