简体   繁体   English

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

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

I have a Net Core 3.1 MVC project where a Playlist can be created and added to an existing Team .我有一个 Net Core 3.1 MVC 项目,可以在其中创建Playlist并将其添加到现有Team I run in to problems when I try to save the Playlist entity with _context.Add(playlist) and then _context.SaveChangesAsync() with the following error:当我尝试使用_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.

My code:我的代码:

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. 

My entities:我的实体:

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

My DbConfig file我的 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);
            
    }
}

In a similar post it was explained that with .Add() EF will treat any objects as new (and so it cannot add an entity with restricted columns twice).在类似的帖子中解释说,使用 .Add() EF 会将任何对象视为新对象(因此它不能两次添加具有受限列的实体)。 However, I don't know how to get this to work.但是,我不知道如何使它起作用。 Loading it untracked vs tracked, setting the Entry().EntityState to Modified or Unchanged doesn't seem to do anything.加载它未跟踪与跟踪,将 Entry().EntityState 设置为 Modified 或 Unchanged 似乎没有做任何事情。

This seems to be a pretty standard thing to do, yet I cannot get it done.这似乎是一件非常标准的事情,但我无法完成。 So, I have a few questions:所以,我有几个问题:

  • Given what I want (a user can add an existing team to a new playlist), do I have the correct relationships defined between Team and Playlist?鉴于我想要什么(用户可以将现有团队添加到新播放列表),我是否在团队和播放列表之间定义了正确的关系?
  • What do I need to use as a statement instead (or in addition to) the Add() statement that I now have?我需要用什么来代替(或补充)我现在拥有的 Add() 语句?

Since you are using net 3.1 you have to add TeamId to由于您使用的是 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);
            });

and use it to assign to playlist并使用它分配到播放列表

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