繁体   English   中英

实体框架核心添加具有相关实体的新实体

[英]entity framework core add new entity with related entity

我有一个 Net Core 3.1 MVC 项目,可以在其中创建Playlist并将其添加到现有Team 当我尝试使用_context.Add(playlist)然后 _context.SaveChangesAsync() 保存Playlist实体时遇到问题,并出现以下错误:

Cannot insert duplicate key row in object 'dbo.Teams' with unique index 'IX_Teams_TeamName'. The duplicate key value is (Team Name Four).
The statement has been terminated.

我的代码:

PlaylistDTO dto = new PlaylistDTO();
dto.Name = "new playlist with related team";
dto.Team = _context.Team.FirstOrDefault(t => t.Id == id) // id comes from viewmodel
Playlist storeToDb = _mapper.Map<Playlist>(dto)
_context.Playlists.Add(storeToDb);
                    
await _context.SaveChangesAsync(); // throws error cannot insert duplicates. 

我的实体:

public class Playlist: AuditEntity
{
    // id comes from AuditEntity
    public string PlayListName { get; set; }
    public string Description { get; set; }

    public Team Team { get; set; }
}

public class Team: AuditEntity
{
    // id comes from AuditEntity
    public string TeamName {get; set; }
    // other properties, including other related entities
    public ICollection<Playlist> Playlists {get; set;}
}

我的 DbConfig 文件

public class TeamDbConfig : IEntityTypeConfiguration<Team>
{
    public void Configure(EntityTypeBuilder<Team> builder)
    {
        builder.ToTable("Teams");

        builder.HasIndex(t => t.TeamName)
            .IsUnique();

        // one2many rel for playlist. One team can have multiple playlists
        builder.HasMany(t => t.Playlists)
            .WithOne(pl => pl.Team)
            .IsRequired(false)
            .OnDelete(DeleteBehavior.Restrict);
            
    }
}

在类似的帖子中解释说,使用 .Add() EF 会将任何对象视为新对象(因此它不能两次添加具有受限列的实体)。 但是,我不知道如何使它起作用。 加载它未跟踪与跟踪,将 Entry().EntityState 设置为 Modified 或 Unchanged 似乎没有做任何事情。

这似乎是一件非常标准的事情,但我无法完成。 所以,我有几个问题:

  • 鉴于我想要什么(用户可以将现有团队添加到新播放列表),我是否在团队和播放列表之间定义了正确的关系?
  • 我需要用什么来代替(或补充)我现在拥有的 Add() 语句?

由于您使用的是 net 3.1,因此您必须将 TeamId 添加到

public class Playlist: AuditEntity
{
    // id comes from AuditEntity
    public string PlayListName { get; set; }
    public string Description { get; set; }

     public int? TeamId { get; set; }
    [ForeignKey(nameof(TeamId))]
    [InverseProperty("Playlists")]
    public virtual Team Team { get; set; }
}

public class Team: AuditEntity
{
    // id comes from AuditEntity
    public string TeamName {get; set; }
    // other properties, including other related entities

    [InverseProperty(nameof(Playlist.Team))]
    public ICollection<Playlist> Playlists {get; set;}
}

[InverseProperty(nameof(FirstClass.SecondClass))]


modelBuilder.Entity<PlayList>(entity =>
            {
                entity.HasOne(d => d.Team)
                   .WithMany(p => p.Playlists)
                   .HasForeignKey(d => d.TeamId);
            });

并使用它分配到播放列表

PlaylistDTO dto = new PlaylistDTO();
dto.Name = "new playlist with related team";
dto.TeamId=id;  // id comes from viewmodel

Playlist storeToDb = _mapper.Map<Playlist>(dto)
_context.Playlists.Add(storeToDb);
await _context.SaveChangesAsync();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM