违反主键,尝试插入外键 table

Violation Primary Key, tries to insert foreign key table

我尝试向规则添加新记录 table。插入规则 table 时,我收到一个错误,好像它试图插入其关系 table。我以前做过类似的插入操作,但我从来没有遇到过这个错误。我也搜索并尝试了其他用户的建议,但对我没有用。

 public class RuleDomainModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]//tried
    public int ObjectID { get; set; }
    public string Name { get; set; }
    //[Key] //tried
    public int? BranchID { get; set; }

    [ForeignKey("BranchID")]//tried
    public virtual BranchDomainModel Branch { get; set; }
}

public class BranchDomainModel : BaseModel
{
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]//tried
    [Key]
    public int ObjectID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<UnitDomainModel> Units { get; set; }
    [ForeignKey("BranchID")]//tried
    public virtual ICollection<RuleDomainModel> Rules { get; set; }
}

映射喜欢;

public void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<RuleDomainModel>().ToTable("Rules");
        builder.Entity<RuleDomainModel>().HasKey(t => t.ObjectID);
        builder.Entity<RuleDomainModel>().Property(t =>t.Name);
        builder.Entity<RuleDomainModel>().HasOne(t => t.Branch).WithMany(t => t.Rules).HasForeignKey(t => t.BranchID).HasPrincipalKey(t => t.ObjectID);
    }

 public void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<BranchDomainModel>().ToTable("Branch");
        builder.Entity<BranchDomainModel>().HasKey(t => t.ObjectID);
        builder.Entity<BranchDomainModel>().Property(t => t.Name);
        builder.Entity<BranchDomainModel>().HasMany(m => m.Units).WithOne(x => x.Branch).HasForeignKey(x => x.xxxID).HasPrincipalKey(m => m.ObjectID);
    }

这就是抛出异常的地方:

if (model.ObjectID == 0)
{
    RuleDomainModel mod = Mapper.Map<RuleDomainModel>(model);
    uow.Repository<RuleDomainModel>().Add(mod);
    uow.Commit(requestOwnerModel); // Cannot insert duplicate key error
}
else
 {
    var mod = Mapper.Map<RuleDomainModel>(model);
    uow.Repository<RuleDomainModel>().Update(mod);
    uow.Commit(requestOwnerModel);
 }

希望有人帮忙,谢谢

我通过在映射到域模型后添加 model.Branch = null 解决了我的问题。但我不知道这是最好的方法。如果有人知道请写在这里。谢谢