将数据添加到EF使用AutoMapper创建的交叉表中

时间:2018-12-18 22:51:55

标签: c# entity-framework-core automapper

这是我的第一个由 Team User TeamUser 对象组成的多对多关系。在 TeamController 中,我将 TeamForCreationDto 映射到 Team ,但是ICollection成员为空。

Q1:EF应该如何组合它以填充所有属性和表?现在,我有了“ for”循环,并在其中创建/添加了TeamUser。

Q2:是否必须同时填写属性AdminId和Admin?
A2:不,添加Admin后,由于EF会自动找到值,因此在数据库中添加了AdminId属性。

ln -sfn /path/to/your/storage/public/ storage

ModelBuilder

中表之间的关系
public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int AdminId { get; set; }
    public User Admin { get; set; }
    //public int[] MembersId { get; set; }
    public ICollection<TeamUser> Members { get; set; }
}
public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public ICollection<Team> TeamsAsAdmin { get; set; }
    public ICollection<TeamUser> TeamsAsMember { get; set; }
}
public class TeamUser
{
    public int TeamId { get; set; }
    public Team Team { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
}

我的 CreateMap AutoMapperProfiles()

builder.Entity<Team>()
    .HasOne(t => t.Admin)
    .WithMany(u => u.TeamsAsAdmin)
    .OnDelete(DeleteBehavior.Restrict);

builder.Entity<TeamUser>()
    .HasKey(tu => new { tu.TeamId, tu.UserId });

builder.Entity<TeamUser>()
    .HasOne(tu => tu.User)
    .WithMany(u => u.TeamsAsMember)
    .HasForeignKey(tu => tu.UserId)
    .OnDelete(DeleteBehavior.Cascade);

builder.Entity<TeamUser>()
    .HasOne(tu => tu.Team)
    .WithMany(t => t.Members)
    .HasForeignKey(tu => tu.TeamId);

我的 TeamController.cs

CreateMap<TeamForCreationDto, Team>().ReverseMap().ForMember(u => u.MembersId, opt => opt.MapFrom(x => x.Members));

TeamForCreationDto.cs

    public async Task<IActionResult> Create(int userId, TeamForCreationDto teamForCreationDto)
    {

        if (await _repoTeams.TeamExists(teamForCreationDto.Name))
            return BadRequest("A team with this name already exists!");
        var mappedTeam = _mapper.Map<Team>(teamForCreationDto);
        //mappedTeam.AdminId = userId;
        mappedTeam.Admin = await _repoUsers.GetUser(userId);
        _repoTeams.Add(mappedTeam);
        for (int i = 0; i < teamForCreationDto.MembersId.Length; i++)
        {
            TeamUser tm = new TeamUser();
            tm.Team = mappedTeam;
            tm.User = await _repoUsers.GetUser(teamForCreationDto.MembersId[i]);
            _repoTeams.Add(tm);
        }
        await _repoTeams.SaveAll();
    }

0 个答案:

没有答案