In this post I will be demonstrating how you can create many to many relationship between classes by using EF code first approach with DataAnnotation attributes. You can use the EF fluent API as well for many to many configuration which I have not covered here. I will be using the classes post and tag in my model which has many to many relationship between them i.e a single post can have many tags and a single tag can have many posts. To get started with many to many configuration between the post and the tag you have to create the classes first. The EF will automatically create the third table when the application will execute, so you will not be creating the third table manually in the model. Let's get started with the code. public class Post { public long PostID { get; set; } [Required] [MaxLength(255)] public string Title { get; set; } [Required] [MaxLength(4000)] [DataType(DataType.MultilineText)] public string Question { g...
If you have a scenario in which you want to base a validation on multiple business logics on multiple properties then you should consider using IValidatableObject . One of the advantages is that you can use the properties attributes directly which open door to a lot of validation possibilities. It will only be called when there are no individual properties error. It doesn't support clientside validation. Below is the simple code that will give you insight of how this all works. public class User : IValidatableObject { [Key] public string UserId { get; set; } [Required] public string UserName { get; set; } [Required] public string Password { get; set; } [Compare("Password")] public string ConfirmPassword { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { List<ValidationResult> err = new List<ValidationResult...