none
many-to-many table using data annotations in ef core RRS feed

  • Question

  • I would like to know how to make a many-to-many relationship using only data annotations

    if you would leave me an example it would be of great help

    Monday, October 19, 2020 10:53 PM

All replies


  • Hi ulises01,
    To configure many-to-many relationship using Data Annotations, you need to create the Join Table in the model.
    Please refer to the following example:
    The Join Table BookCategory will have properties for the primary key of both the table.
    It will have two navigational properties one each for Book and Category class.
    The Book and Category class will have the navigational property which maps to the Join Table BookCategory.

    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public virtual ICollection<BookCategory> BookCategories { get; set; }
    }
    
    public class Category
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public virtual ICollection<BookCategory> BookCategories { get; set; }
    }
    
    public class BookCategory
    {
        [Key, Column(Order = 1)]
        public int BookId { get; set; }
        [Key, Column(Order = 2)]
        public int CategoryId { get; set; }
        public Book Book { get; set; }
        public Category Category { get; set; }
    }

    It will create Books, Categories and BookCategories tables in the database. The BookCategories table will have composite key BookId and CategoryId.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, October 20, 2020 3:25 AM
  • Hi ulises01,
    Has your problem been solved? If it is resolved, we suggest that you mark it as the answer. So it can help other people who have the same problem find a solution quickly.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 22, 2020 7:48 AM
  • Hello,

    If you are still working on this, check out the following article and code sample which explains how to make use of data annotations for ASP.NET MVC. Search for "Creating Job Application" Controller. Also there are decent examples for customizing attributes.

    Here is an example of a custom attribute for SSN.

    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Text.RegularExpressions;
    
    namespace ValidationLibrary.CommonRules
    {
        /// <summary>
        /// Is a valid SSN
        /// </summary>
        /// <returns>True if valid, false if invalid SSN</returns>
        /// <remarks>
        ///
        /// Handle some commonly encountered “fake” values or ones that might easily be forged in
        /// an area that might require a user to enter one.
        /// 
        /// ^                                       #Start of expression
        /// (?!\b(\d)\1+-(\d)\1+-(\d)\1+\b)         #Don't allow all matching digits for every field
        /// (?!123-45-6789|219-09-9999|078-05-1120) #Don't allow "123-45-6789", "219-09-9999" or "078-05-1120"
        /// (?!666|000|9\d{2})\d{3}                 #Don't allow the SSN to begin with 666, 000 or anything between 900-999
        /// -                                       #A dash (separating Area and Group numbers)
        /// (?!00)\d{2}                             #Don't allow the Group Number to be "00"
        /// -                                       #Another dash (separating Group and Serial numbers)
        /// (?!0{4})\d{4}                           #Don't allow last four digits to be "0000"
        /// $                                       #End of expression
        /// </remarks>
        [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
        public class SocialSecurityAttribute : ValidationAttribute
        {
            public string SocialValue { get; set; }
    
            public override bool IsValid(object value)
            {
                return value is string && (!(value is null) && Regex.IsMatch(value.ToString().Replace("-", ""),
                    @"^(?!\b(\d)\1+\b)(?!123456789|219099999|078051120)(?!666|000|9\d{2})\d{3}(?!00)\d{2}(?!0{4})\d{4}$"));
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    Sunday, November 1, 2020 10:24 PM