【发布时间】:2014-04-14 23:25:08
【问题描述】:
我有一个从数据库生成的实体框架模型。其中一个实体是具有“Type”int 属性的“Session”。
自动生成的类:
public class Session
{
int Type { get; set;}
}
Edmx:
<EntityType Name="Sessions">
<Property Name="Type" Type="int" Nullable="false" />
</EntityType>
有时在加载数据库值时,我会收到一个异常,指出它无法将“类型”属性(即 int)设置为“字符串”值:
System.InvalidOperationException:“Session”上的“Type”属性无法设置为“System.String”值。您必须将此属性设置为“System.Int32”类型的非空值。在 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](Func2constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) 在 lambda_method(Closure, Shaper) 在 System.Data.Entity.Core.Common.Internal。 Materialization.Coordinator1.ReadNextElement(Shaper shaper) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source)
这是失败的查询:
var session = db.Sessions.Include("Game.Mod").Where(s => s.UniqueId == message.SessionUid && s.DomainId == this.DomainId && s.Game.UniqueId == message.GameUid).FirstOrDefault();
在本地调试时,一切正常。这是部署到产品时。
我目前在 sql azure 上使用 EF 6.1,我认为这可能与升级有关,我认为以前没有发生过这种情况(使用 6.1)。但我可能错了。
数据库列也是一个int(100%确认),映射是正确的。
【问题讨论】:
-
您的数据库同步吗?正如您提到的产品 - 似乎您的产品数据库针对的是早期代码,并且在您现在拥有整数的地方有一些字符串。 “物化”错误表明它无法将 db 字段值“物化”到对象属性中。至少,看起来是这样的。此外,如果/在重新配置模型、关系时可能会出现类似的问题,但这里似乎并非如此
-
prod db 列也是一个int,刚刚检查。该模型已更新,在最新版本中添加了其他列。但是,这不应该影响现有的“类型”列,它没有改变。请记住,我已经在本地针对 prod DB 运行了它,它工作正常
-
我知道,但是同步问题的“气味”——迁移并保持同步并不像 EF 那样简单——你有“迁移”表、代码和 Db,三件事真的(不确定最新的 EF 版本是否改变了某些东西,但对此表示怀疑)。这是我的一篇关于它的帖子仅供参考how to sync
-
我没有使用 Code First,没有迁移。模型是从数据库生成的。
-
数据库列是否允许空值?如果是这样,您的模型属性必须定义为
int?我只是键入异常的“将此属性设置为非空值”部分。
标签: c# .net entity-framework