简体   繁体   中英

Validation many to many relationship ef core

I want to know if there's a way to add a validator where an author needs to be selected on a combobox otherwise it will display an error.

In my application I have three models, Books, Authors and the join table Rel_Book_Author.

public class Book
{
    [Key]
    [Display(Name = "Id")]
    [Column("book_id")]
    public int book_id { get; set; }

    [Display(Name = "Title")]
    [Column("liv_title")]
    [Required(ErrorMessage = "Every book needs a title")]
    public string liv_title { get; set; }
}

public class Author
{
    [Key]
    [Display(Name = "Id")]
    [Column("aut_id")]
    public int aut_id { get; set; }

    [Display(Name = "Author's Name")]
    [Column("aut_name")]
    public string aut_name { get; set; }

    public ICollection<Rel_Book_Author> BookAuthors { get; set; }
}

public class Rel_Book_Author
{
    [Column("hla_aut_id")]
    public int aut_id { get; set; }
    public Author Author { get; set; }

    [Column("hla_book_id")]
    public int book_id { get; set; }
    public Book Book { get; set; }

}

I'm making the assumption here that your view's model will be the Rel_Book_Author class, or a list of those classes, and so you the view shows a book (or books) and allows the user to pick the author from a list for each book?

If so, then validation should work as per any other model with data annotations .

EF Core does not perform any validations itself , it expects you to do have already validated the object using the client-side validation and on the server (typically in the controller), so the fact that the objects are related by a particular type of relationship (eg many-to-many) doesn't matter here.

There is one gotcha to watch out for with the Required attribute for an integer; which is that a non-nullable integer (obviously) cannot be null, it will just default to zero, which means that setting Required won't actually ever return a validation error for an integer in a select list (as the property will always have a value of zero or the value of whatever is selected in the list).

To get round that, declare the aut_id property as nullable ( int? ):

[Required]
public int? aut_id { get; set; }

or add a Range attribute, eg

[Range(1, int.MaxValue)]
public int? aut_id { get; set; }

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