简体   繁体   中英

How to update a linked table in entity framework

I am using EF code first approach and have a domain model class as:

 public class WindmillUser
        {
            public WindmillUser()
            {
            AssignedMsos = new Collection<Mso>();
            RepackerHeaders = new Collection<RepackerHeader>();
        }
        public int WindmillUserId {get;set;}
        public string Username { get; set; }
        public RoleType Role { get; set; }
        public string Email { get; set; }
        public bool Active { get; set; }
        public DateTime? LastInteraction { get; set; }
        public string TelephoneNumber { get; set; }
        public virtual ICollection<Mso> AssignedMsos { get; set; }
        public virtual ICollection<RepackerHeader> RepackerHeaders { get; set; }
        public virtual ICollection<WindmillUser> WindmillUserImpersonateParent { get; set; }
        public virtual ICollection<WindmillUser> WindmillUsersImpersonateChild { get; set; }
   }
}

I have the following configuration in the datacontext class:

modelBuilder.Entity<WindmillUser>().HasMany(entity => entity.WindmillUsersImpersonateChild).WithMany(child => child.WindmillUserImpersonateParent)
                .Map(map =>
                    {
                        map.ToTable("WindmilUserImpersonate");
                        map.MapLeftKey("WindmillUserImpersonateParentId");
                        map.MapRightKey("WindmillUsersImpersonateChildId");
                    });

This creates a table WindmillUserImpersonate in the database which stores the many to many relationship of WindmillUser table to itself.

I want to insert the records in WindmillUserImpersonate table. Do I need to create a domain model for WindmillUserImpersonate to do operations and if yes then is the following domain correct?

public class WindmillUserImpersonate
    {
        public int WindmillUserImpersonateParentId { get; set; }
        public int WindmillUsersImpersonateChildId { get; set; }
        public virtual WindmillUser WindmillUser { get; set; }
    }

And if there is no need to create a WindmillUserImpersonate class then how can I Insert/update the WindmillUserImpersonate table?

If you have entity WindmillUser user and want to add new parent childUser, you should do:

user.WindmillUsersImpersonateChild.Add(childUser);
context.SaveChanges();

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