EFCore-使用子实体记录保存实体

时间:2018-04-12 11:25:59

标签: entity-framework automapper unit-of-work ef-core-2.0

以下是我的模特:

    public partial class UserDTO
    {
     public int UserId { get; set; }
     public ICollection<Userskills> Userskills { get; set; }
    }

 public partial class SkillsmasterDTO
    {
        public sbyte SkillId { get; set; }
        public string Skill { get; set; }
        public ICollection<Userskills> Userskills { get; set; }
   }


  public partial class UserskillsDTO
    {
        public int UserId { get; set; }
        public sbyte SkillId { get; set; }

        public SkillsmasterDTO Skill { get; set; }
        public UsermasterDTO User { get; set; }
    }

 public class UserMaster
    {
     public int UserId { get; set; }
     public List<UserSkills> UserSkills{get;set;}
    //other fields
    }

 public class SkillsMaster
 {
        public sbyte SkillId { get; set; }
        public string Skill { get; set; }
 }

    public class UserSkills
    {
        public int UserId { get; set; }
        public sbyte SkillId { get; set; }
        public string Skill { get; set; }
    }

我想要保存UserMaster,以及我想要同时保存UserSkills。 我按以下格式发送数据:

{"FirstName": "Priya",
"LastName": "Dave",
"Email":"priya.dave@xyz.com",
"Password":"123456",
"ContactNo":"1234",
"RoleId":1,
"CreatedBy":15,
"UserTypeId":2,
"LocationId":1,
"BandId":1,
"PostId":1,
"IsActive":1,
"UserSkills":[{"SkillId":1}]
}

我为保存编写的代码是:

 var insertedEmployee= unitOfWork.UserRepository.Add(Mapper.Map<Usermaster>(employee));

_unitOfWork.Save();

它正在保存用户详细信息,但UserSkills未保存。我怎样才能做到这一点?我浏览了一些博客,但无法找到合适的解决方案。

1 个答案:

答案 0 :(得分:0)

由于UserSkills保留在与UserMaster不同的表中,因此您需要为工作单元执行以下操作。

  1. UserMaster添加到context.UserMasters表格
  2. UserSkills添加到context.UserSkills表格
  3. UserSkills添加到context.UserMaster对象
  4. 然后context.SaveChanges()