为什么EF核心无效的实体原因是“预期类型是system.String'但是实际价值是无效的?”
之间有多一关系
modelBuilder.Entity<Party>()
.HasMany(p => p.PartyMembers)
.WithOne(p => p.Party);
使用实体框架6和.NET 6,我在party
和statentity 有一个
party
:
[NotLogged] [JsonIgnore] public Party? Party { get; set; }
的确,我们可以看到party
根据自动生成的迁移而配置为无效:
migrationBuilder.AlterColumn<string>(
name: "PartyId",
table: "StatEntities",
type: "varchar(36)",
nullable: true,
oldClrType: typeof(string),
oldType: "varchar(36)")
.Annotation("MySql:CharSet", "latin1")
.OldAnnotation("MySql:CharSet", "latin1");
- 根据
__ __ efmigrations history
,迁移是成功应用。 - 数据库中存在
null
party>的值。
但是,当我尝试查询statentity
具有null
的值party> party
时,我会收到以下内容:
在读取属性'statentity.partyid'的数据库值时发生错误。预期的类型为“系统。弦”,但实际值为null。
请注意,我是不是尝试.include(statentity =&gt; statentity.party)
。似乎EF Core不允许为影子属性提供零值,即使它被称为此类属性。
Using Entity Framework 6 and .NET 6, I have a many-to-one relationship between Party
and StatEntity
:
modelBuilder.Entity<Party>()
.HasMany(p => p.PartyMembers)
.WithOne(p => p.Party);
Where the StatEntity
may not necessarily have a Party
:
[NotLogged] [JsonIgnore] public Party? Party { get; set; }
Indeed, we can see that PartyId
is configured as nullable based upon the auto generated migration:
migrationBuilder.AlterColumn<string>(
name: "PartyId",
table: "StatEntities",
type: "varchar(36)",
nullable: true,
oldClrType: typeof(string),
oldType: "varchar(36)")
.Annotation("MySql:CharSet", "latin1")
.OldAnnotation("MySql:CharSet", "latin1");
- According to
__EFMigrationsHistory
, the migration was successfully applied. - There exist
null
values forPartyId
in the database.
However, when I try to query a StatEntity
that has a null
value for PartyId
, I receive the following:
An error occurred while reading a database value for property 'StatEntity.PartyId'. The expected type was 'System.String' but the actual value was null.
Note that I am not attempting to .Include(statEntity => statEntity.Party)
. It seems that EF Core is not allowing null values for the shadow property, even though it is declared as such.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一个工作障碍,明确定义
statentity
上的影子属性似乎可以解决该问题:奇怪的是,运行
dotnet ef ef迁移添加blah
创建一个空迁移,因此肯定数据库方面没有错。它似乎是EFCORE中的一个错误,它导致基础阴影属性无法正确定义为无效。As a work-around, explicitly defining the shadow property on the
StatEntity
appears to fix the problem:Curiously, running a
dotnet ef migrations add blah
creates an empty migration, so definitely nothing wrong with the database aspect. It appears to be a bug in EFCore that causes the underlying shadow property to not be correctly defined as nullable.