简体   繁体   English

.Net Core 6 ModelState.IsValid 被标记为无效时

[英].Net Core 6 ModelState.IsValid Flagged As Not Valid When It Is

When trying to create a new record for USER, ModelState.IsValid is flagged as invalid.尝试为 USER 创建新记录时,ModelState.IsValid 被标记为无效。 However, all the correct data is there.但是,所有正确的数据都在那里。

The issue seems to be in Reference Key.问题似乎在 Reference Key 中。

My Classes我的课程

   public class Users
   {
    [Key]
    public int IdUser { get; set; }
    public int IdLOB { get; set; }
    public string Email { get; set; } = default!;
    public string FullName { get; set; } = default!;
    public string? Nickname { get; set; }
    public DateTime ModifiedOn { get; set; }

    [ForeignKey("IdLOB")]
    public virtual LOBS IdLOBNavigation { get; set; } = default!;
   }

public class LOBS
{
    [Key]
    public int IdLOB { get; set; }
    public string LOB { get; set; } = default!;
    public int? ParentLOB { get; set; }

    [Display(Name = "Parent LOB")]
    [ForeignKey("ParentLOB")]
    public virtual LOBS? ParentLOBNavigation { get; set; }
}

All data is passed to Users, including IdLOB, but it flagged as invalid because of IdLOBNavigation:所有数据都传递给用户,包括 IdLOB,但由于 IdLOBNavigation,它被标记为无效:

在此处输入图像描述

If I jump model validation, the data is processed without error and the record is created.如果我跳转 model 验证,数据处理无误并创建记录。 Also, the tables in the database are correct, IdLOBNavigation is a relation and not a field.此外,数据库中的表是正确的,IdLOBNavigation 是一个关系而不是一个字段。

So I believe the error is in how I'm declaring the relation in the Users Class. What is the correct way to do this in.Net 6所以我认为错误在于我在用户 Class 中声明关系的方式。在 .Net 6 中执行此操作的正确方法是什么

I'm making an assumption that you are passing the domain model to an API endpoint and then adding that model to your context and trying to save.我假设您将域 model 传递给 API 端点,然后将该 model 添加到您的上下文并尝试保存。

If that is the case, then I think you need to create a request model to take in only the data you need, rather than the actual domain model. You then validate the request model with the limited dataset that you want the end user to be able pass in to be saved.如果是这种情况,那么我认为您需要创建一个请求 model 以仅接收您需要的数据,而不是实际域 model。然后您使用您希望最终用户使用的有限数据集验证请求 model能进去得救。 Ie IdLOB , email , fullname , nickname .IdLOBemailfullname名, nickname

That way you limit the end user from being able to set properties they shouldn't (ie ModifiedOn ), can validate your request model explicitly (as we never trust the client) and create a new instance of User (via constructor or mapper like AutoMapper) which is safe to be added to your context.这样你就可以限制最终用户设置他们不应该设置的属性(即ModifiedOn ),可以明确地验证你的请求 model (因为我们从不信任客户端)并创建一个新的 User 实例(通过构造函数或像 AutoMapper 这样的映射器) 可以安全地添加到您的上下文中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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