我当前正在尝试通过WCF服务使用OData和Entity Framework返回dbset。我可以在数据上下文中点击dbset属性上的getter,但是当它返回时会出现错误:
LINQ to Entities仅支持强制转换EDM基本类型或枚举类型
最初,我认为这是由于我在实体模型中具有可为空的外键,但是在删除所有可为null的int类型之后,我仍然会收到错误消息。
MyDataContext.cs
public class MyDataContext : DbContext, IMyDataContext, IMyDbContextFactory
{
/// <summary>
/// Default Constructor
/// </summary>
public MyDataContext()
{
}
/// <summary>
/// ConnectionString Constructor
/// </summary>
/// <param name="connectionString">Sets the initial connection string</param>
public MyDataContext(string connectionString) : base(connectionString)
{
this.ConnectionString = connectionString;
}
public string ConnectionString { get; set; }
#region Global Resources
public DbSet<MyResource> MyResource{ get; set; }
#region Ranges
public DbSet<TheRanges> TheRanges { get; set; }
public DbSet<TheRangesSub> TheRangesSub { get; set; }
#region EF Model Configuration
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.RegisterEntityType(typeof(MyResource));
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
base.OnModelCreating(modelBuilder);
}
}
MyResource.cs
[Table("MyResource")]
[DataServiceKey("Id")]
public class MyResource
{
[Key]
public int Id { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string Title { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string MyResource { get; set; }
public string Description { get; set; }
[Required]
public bool SomeStandard { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string CreatedDateTime { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string ModifiedDateTime { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
}
TheRanges.cs
[Table("TheRanges")]
[DataServiceKey("Id")]
[EnableQuery]
public class TheRanges
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
[Required]
public int MyResourceId { get; set; }
[ForeignKey(nameof(MyResourceId))]
public MyResource MyResource { get; set; }
[Required]
public int someIntField { get; set; }
public string LinkId { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string CreatedDateTime { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string ModifiedDateTime { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
}
TheRangesSub.cs
[Table("TheRangesSub")]
[DataServiceKey("Id")]
public class TheRangesSub
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
[Required]
public int TheRangesId { get; set; }
[ForeignKey(nameof(TheRangesId))]
public TheRanges TheRanges { get; set; }
public string FacilityNum { get; set; }
[Required]
public int SomeOtherInt { get; set; }
public string LinkId { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string RangeName { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string CreatedDateTime { get; set; }
[MaxLength(255)]
[Required(AllowEmptyStrings = true)]
public string ModifiedDateTime { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
}
MyService.cs
[BasicHttpBindingServiceMetadataExchangeEndpoint]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, IncludeExceptionDetailInFaults = true)]
public class MyService : DataService<MyDataContext>
{
private SPWeb _web;
private string connectionString;
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public MyService() : base()
{
}
#endregion
#region Methods
protected override MyDataContext CreateDataSource()
{
return new MyDataContext("MyConnectionString");
}
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("TheRanges", EntitySetRights.AllRead);
config.SetEntitySetAccessRule("TheRangesSub", EntitySetRights.AllRead);
config.SetEntitySetAccessRule("MyResource", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = System.Data.Services.Common.DataServiceProtocolVersion.V2;
config.UseVerboseErrors = true;
}
#endregion
让我知道我更改名字时是否发生命名不一致
我的MyResource数据库中有1个项目,因此我希望将其退回。 我正在执行的OData查询是: http://myurl/MyData.svc/MyResource?$ select = Id
运行调试器时,代码中最后被击中的地方是“ get”:
DbSet<MyResource> MyResource {get; set;}
但是,这是我当前遇到的错误:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code/>
<message xml:lang="en-US">An error occurred while processing this request.</message>
<innererror>
<message>
Unable to cast the type 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
</message>
<type>System.NotSupportedException</type>
<stacktrace>
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ValidateAndAdjustCastTypes(TypeUsage toType, TypeUsage fromType, Type toClrType, Type fromClrType)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.GetCastTargetType(TypeUsage fromType, Type toClrType, Type fromClrType, Boolean preserveCastForDateTime)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.CreateCastExpression(DbExpression source, Type toClrType, Type fromClrType)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ConvertTranslator.TranslateUnary(ExpressionConverter parent, UnaryExpression unary, DbExpression operand)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.ConditionalTranslator.TypedTranslate(ExpressionConverter parent, ConditionalExpression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SelectTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Data.Services.DataService`1.SerializeResponseBody(RequestDescription description, IDataService dataService)
at System.Data.Services.DataService`1.HandleRequest()
</stacktrace>
</innererror>
</error>
编辑:因此,仅使用查询字符串“ http://myurl/MyData.svc/MyResource”就可以从数据库中检索我的商品,但是由于以下原因,我无法使用$ select和一些属性来获取商品:无法转换类型错误。我也可以在实体上运行$ filter和$ count。看来这只是一个$ select问题。