none
EntityTypeConfiguration and Many to Many Relationship with additional field RRS feed

  • Question

  • I have a domain model with the following structure 

    public class ObjectOne
        {
            public int ObjectOneId { get; set; }
            public string ObjectOneName { get; set; }
        }
    
        public class ObjectTwo
        {
            public int ObjectTwoId { get; set; }
            public string ObjectTwoName { get; set; }
        }
    
        public class ObjectOneObjectTwo
        {
            public int ObjectOneId { get; set; }
            public int ObjectTwoId { get; set; }
            public DateTime AddedDate { get; set; }
    
            public virtual ObjectOne ObjectOne { get; set; }
            public virtual ObjectTwo ObjectTwo { get; set; }
    
        }

    I want My ObjectOneObjectTwo entity to have its own table and I want to make the three fields (ObjectOneId, ObjectTwoId, AddedDate) Primary key... which mean there could be the same ObjectOne and ObjectTwo may happen on different time. 

    How Could I define such cases on EntityTypeConfiguration due to I dont want to make my OnModelCreating() method spaghetti1 


    Binyam Welday

    Tuesday, March 18, 2014 9:00 AM

Answers

  • Hello bcompt143,

    I am trying to help look into this issue.

    >>How Could I define such cases on EntityTypeConfiguration due to I dont want to make my OnModelCreating() method spaghetti1

    For mapping many to many relationship with additional fields in Code First, the main idea is that we need to create two one to many relationships, it does not matter whether we use the EntityTypeConfiguration class or OnModelCreating() method, in your case:

    ObjectOne : ObjectOneObjectTwo => N:1, ObjectTwo : ObjectOneObjectTwo => N:1,

    Then it needs us to add a collection type in both ObjecOne and ObjectTwo classes as:

    public virtual ICollection<ObjectOneObjectTwo> ObjectOneObjectTwos{ get; set; }

    In the EntityTypeConfiguration class of the junction table, (in your case)to define ObjectOneId, ObjectTwoId, AddedDate these three columns to be primary key.

    In the EntityTypeConfiguration classes of ObjectOne and ObjectTwo, to define the one to many relationship between ObjectOne/ObjectTwo with ObjectOneObjectTwo and specify the foreign key.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, March 19, 2014 2:31 AM
    Moderator