简体   繁体   中英

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.

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. I attach the entity to my DbContext and it will by updated. 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. I cannot skip the Id field from the ReadBlockDefinition ViewModel because it is essential for updates.

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. 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.

Any ideas how to overcome this? Or is the ModelState.Remove(...) approach the intended one?

Have you considered setting the data annotations for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM