Home > Blockchain >  Model validation issues on foreign key object references
Model validation issues on foreign key object references

Time:04-21

I'm starting checking out asp.net 6 / mvc / entity framework application and am running into trouble with just a basic test application. My foreign key object (not the ID itself) is making my ModelState.Isvalid false on the Create of a Scaffolded Controller.

Changed a few field names for simplicity, but it is basically this with a few extra strings in the model - picture a user with a required department:

[Column("deptId")]
public int DeptId { get; set; } // <== ValidationState = Valid

[ForeignKey("DeptId")]
[InverseProperty("Users")]
public virtual Dept dept { get; set; } = null!; // <== ValidationState = InValid

Model was created with a Scaffold-DbContext.

I can do a "ModelState.Remove("Dept")" and everything passes.

I can recreate exactly in asp.net 3.1 and it has no issues. The virtual Dept object isn't checked but it is in asp.net 6. Is this now expected? Is there a fix or a better way than applying a ModelState.Remove for every foreign key Object on every create? Am I missing something new that is telling that field to be validated?

CodePudding user response:

try to set the property as follow:

public virtual Dept? dept { get; set; }

also you could create a viewmodel

  • Related