[英]ASP.NET Core Razor PageModel ModelState Invalid because of new Navigation Property with Id==0
I'm trying to update an entity that may have an optional NavigationProperty from an html form.我正在尝试从 html 表单更新可能具有可选 NavigationProperty 的实体。
public class ProcessDataGroup
{
public int Id { get; set; }
public string Name { get; set; }
public ReadDataGroupStrategy ReadDataGroupStrategy { get; set; }
public ReadBlockDefinition ReadBlockDefinition { get; set; }
public int? ReadBlockDefinitionId { get; set; }
}
public class ReadBlockDefinition
{
public int Id { get; set; }
public string Address { get; set; }
public int Length { get; set; }
public int Offset { get; set; }
}
If ReadBlockDefinition
already exists and has an Id > 0
, this works.如果
ReadBlockDefinition
已经存在并且Id > 0
,则此方法有效。 I attach the entity to my DbContext
and it will by updated.我将实体附加到我的
DbContext
并且它将被更新。 But it is possible that in the html form the ReadDataGroupStrategy
is changed and then a new ReadBlockDefinition
is created, that by default of course has an Id
of 0. In this case ModelState.IsValid
will return false und investigation during debugging discovers that is it complaining about the ReadBlockDefinition.Id
field, so it seems it won't accept 0 there.但是有可能在 html 表单中更改了
ReadDataGroupStrategy
,然后创建了一个新的ReadBlockDefinition
,默认情况下它的Id
为 0。在这种情况下, ModelState.IsValid
将返回 false,调试期间的调查发现它在抱怨关于ReadBlockDefinition.Id
字段,所以它似乎不会接受 0 那里。 I cannot skip the Id field from the ReadBlockDefinition
ViewModel because it is essential for updates.我不能跳过
ReadBlockDefinition
ViewModel 中的 Id 字段,因为它对于更新至关重要。
My workaround at the moment is我目前的解决方法是
if(ProcessDataGroup?.ReadBlockDefinition?.Id == 0)
ModelState.Remove("ProcessDataGroup.ReadBlockDefinition.Id");
before evaluating ModelState.IsValid
but this seems a rather strange solution to me.在评估
ModelState.IsValid
之前,但这对我来说似乎是一个相当奇怪的解决方案。 I'm generally not sure why validation fails in the first place.我通常不确定为什么验证首先会失败。 As I understood so far, validation isn't related to EF Core or whatever underlying technology and 0 should be a perfectly valid integer.
据我所知,验证与 EF Core 或任何底层技术无关,0 应该是完全有效的 integer。
Any ideas how to overcome this?任何想法如何克服这个问题? Or is the
ModelState.Remove(...)
approach the intended one?还是
ModelState.Remove(...)
方法是预期的?
Have you considered setting the data annotations for Id?您是否考虑过为 Id 设置数据注释?
public class ReadBlockDefinition
{
[Key]
public int Id { get; set; }
public string Address { get; set; }
public int Length { get; set; }
public int Offset { get; set; }
}
https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.