对列类型感到困惑

时间:2014-04-14 23:25:09

标签: c# .net entity-framework

我有一个从数据库生成的实体框架模型。其中一个实体是会话'用' Type' int property。

自动生成的课程:

public class Session
{
    int Type { get; set;}    
}

EDMX:

<EntityType Name="Sessions">
      <Property Name="Type" Type="int" Nullable="false" />
</EntityType>

有时在加载数据库值时,我会收到一个例外情况,说它无法设置&#39; Type&#39;属性(即int)到一个&#39;字符串&#39;值:

  

System.InvalidOperationException:&#39; Type&#39;会议&#39;会议&#39;无法设置为System.String&#39;值。您必须将此属性设置为类型为&#39; System.Int32&#39;的非空值。 at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader 1.GetValue(DbDataReader reader, Int32 ordinal) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName) at lambda_method(Closure , Shaper ) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func 2 constructEntityDelegate,EntityKey entityKey,EntitySet entitySet)位于System.Data.Entity.Core.Common的lambda_method(Closure,Shaper)。 Internal.Materialization.Coordinator 1.ReadNextElement(Shaper shaper) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper 1.SimpleEnumerator.MoveNext()在System.Linq.Enumerable.FirstOrDefault [TSource](IEnumerable 1 source) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable 1 source)

这是失败的查询:

var session = db.Sessions.Include("Game.Mod").Where(s => s.UniqueId == message.SessionUid && s.DomainId == this.DomainId && s.Game.UniqueId == message.GameUid).FirstOrDefault();

在本地调试时,一切正常。这是在部署到prod时。

我目前在sql azure上使用EF 6.1,我认为这可能与升级有关,我不认为这是在发生之前(使用6.1)。但我可能错了。

数据库列也是一个int(100%确认),映射是正确的。

1 个答案:

答案 0 :(得分:5)

错误消息的第一部分

  

System.InvalidOperationException:&#39; Type&#39;会议&#39;会议&#39;   无法设置为System.String&#39;值。

第一句话暗示在intstring的某个时间点尝试转换。您的数据库字段和属性是ints。我相信你,但EF试图转换。

尝试将查询保存到变量并在另一行执行FirstOrDefault()

var query = db.Sessions.Include("Game.Mod").Where(s => s.UniqueId == message.SessionUid && s.DomainId == this.DomainId && s.Game.UniqueId == message.GameUid);
var session = query.FirstOrDefault();

然后尝试保存在数据库中执行查询之前生成的SQL。这可能会给你一个线索。

错误消息的第二部分

  

您必须将此值设置为&#39; System.Int32&#39;

类型的非空值

要解决您的问题,。Net建议您将变量设置为非空值。这是因为数据库中不允许使用空值...

您是否尝试将字段设为nullable

不要忘记检查您是否在数据库和代码中进行了更改。


其他见解&#34;可能&#34;有用

此外,我很想冒险说您在生产中遇到问题但在本地没有,因为您有不同的数据。不要忘记在尝试对数据执行某些操作时会发生运行时异常。

相关问题