如何在实体框架中更新链接表

时间:2015-10-15 12:18:46

标签: c# entity-framework

我使用EF代码第一种方法,并将域模型类设为:

 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; }
   }
}

我在datacontext类中有以下配置:

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

这会在数据库中创建一个表WindmillUserImpersonate,它存储WindmillUser表与其自身的多对多关系。

我想在WindmillUserImpersonate表中插入记录。我是否需要为WindmillUserImpersonate创建一个域模型来执行操作?如果是,那么以下域是否正确?

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

如果不需要创建WindmillUserImpersonate类,那么如何插入/更新WindmillUserImpersonate表?

1 个答案:

答案 0 :(得分:1)

如果你有实体WindmillUser用户并且想要添加新的父childUser,你应该这样做:

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