c# - 无法通过将自己指定为父级来确定相关操作的有效顺序

标签 c# .net entity-framework ef-code-first

当我尝试将自己指定为插入的父对象时出现以下错误。

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

代码如下。我以为我可以做到这一点,但我想我做不到。我怎样才能在插入件上执行此操作?

public class Team {

    public int? TeamParentId { get; set; }

    [ForeignKey("TeamParentId")]
    public virtual Team TeamParent { get; set; }

    public virtual ICollection<Team> Teams { get; set; }
}

错误发生的地方

    divisionTeam.Team.TeamParent = divisionTeam.Team;

 if (divisionTeam.Id == 0)
            {
                _divisionTeamsRepository.Add(divisionTeam);
            }

            UnitOfWork.Commit();

DataContext.cs

modelBuilder.Entity<Team>()
    .HasOptional(p => p.TeamParent)
    .WithMany(p => p.Teams)
    .HasForeignKey(q => q.TeamParentId);

我怎样才能做到这一点?

最佳答案

似乎您设置团队的方式正在创建一个循环,EF“不可能”“保存”该循环。

如果您询问如何实际完成此操作,那么您必须实际保存没有父级的 Team 并在 SaveChanges() 方法之后分配其 IdTeamParentId,像这样:

var team = new Team(....);

db.Teams.Add(team);

team.TeamParentId = team.Id;

db.SaveChanges();

我知道这看起来很复杂,但这是我能想到的唯一方法。希望对你有帮助

关于c# - 无法通过将自己指定为父级来确定相关操作的有效顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45763265/

相关文章:

c# - Visual Studio 2010 的问题

c# - 在 linq 中构建对象 - 添加依赖于其他属性的属性

.net - 我可以从 FTP 服务器或 HTTP 服务器读取文件作为流吗?

c# - 使用 EF6 在运行时连接到 SQL Server - 部分类构造函数的问题

c# - 从 url 加载和显示图像

c# - 异常 : Application initializing document picker is missing the iCloud entitlement. 是否设置了 com.apple.developer.icloud-container-identifiers?

c# - 如何创建 .NET 4 MVC 3 作业/队列系统?

.net - 创建泛型类型的泛型列表

c# - 将表类型作为 T 传递给通用列表

javascript - 序列化、反序列化 C#/JSON 对象并且没有大小写问题