[英]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.在我的应用程序中,我有三个模型:书籍、作者和连接表 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?我在这里假设您的视图模型将是
Rel_Book_Author
类或这些类的列表,因此您的视图显示一本书(或多本书)并允许用户从每本书的列表中选择作者?
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. EF Core本身不执行任何验证,它希望您已经使用客户端验证和在服务器上(通常在控制器中)验证了对象,因此对象通过特定类型的关系相关联的事实(例如多对多)在这里无关紧要。
There is one gotcha to watch out for with the Required
attribute for an integer;整数的
Required
属性有一个需要注意的问题; 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).这是一个不可为空的整数(显然)不能为空,它只会默认为零,这意味着设置
Required
不会实际上返回选择列表中整数的验证错误(因为该属性将始终具有零值或列表中选择的任何值)。
To get round that, declare the aut_id
property as nullable ( int?
):为了解决这个问题,将
aut_id
属性声明为可空( int?
):
[Required]
public int? aut_id { get; set; }
or add a Range
attribute, eg或者添加一个
Range
属性,例如
[Range(1, int.MaxValue)]
public int? aut_id { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.