Как правильно настроить множественные отношения один-к-одному? - PullRequest
1 голос
/ 15 марта 2020

У меня есть объекты DbDropPhoto, DbReferencePhoto и DbSimpleLine. DbSimpleLine может храниться в базе данных в трех разных состояниях: DropPhotoHor horizontalLine, DropPhotoVerticalLine, DbReferencePhoto. Каждое из этих состояний отменяет друг друга. Например, для SimpleLine, являющейся DropPhotoVerticalLine, для DropPhotoHor horizontalLine и DbReferencePhoto задано значение null:

[Table("DropPhotos")]
    public class DbDropPhoto
    {
        [Key]
        public Guid DropPhotoId { get; set; }

        public int ZDiameterInPixels { get; set; }
        public virtual DbSimpleLine SimpleHorizontalLine { get; set; }
        public virtual DbSimpleLine SimpleVerticalLine { get; set; }
    }

    public class DbReferencePhoto
    {
        [Key]
        public Guid ReferencePhotoId { get; set; }

        public virtual DbSimpleLine SimpleLine { get; set; }
    }

[Table("SimpleLines")]
public class DbSimpleLine
{
    [Key]
    public Guid SimpleLineId { get; set; }

    public virtual DbReferencePhoto ReferencePhoto { get; set; }
    public virtual DbDropPhoto DropPhotoHorizontalLine { get; set; }
    public virtual DbDropPhoto DropPhotoVerticalLine { get; set; }
}

моя текущая конфигурация:

        modelBuilder.Entity<DbDropPhoto>()
            .HasRequired(s => s.SimpleHorizontalLine)
            .WithRequiredPrincipal(ad => ad.DropPhotoHorizontalLine);

        modelBuilder.Entity<DbDropPhoto>()
            .HasRequired(s => s.SimpleVerticalLine)
            .WithRequiredPrincipal(ad => ad.DropPhotoVerticalLine);

        modelBuilder.Entity<DbReferencePhoto>()
            .HasRequired(s => s.SimpleLine)
            .WithRequiredPrincipal(ad => ad.ReferencePhoto);

Я пытаюсь сохранить новую dbSimpleLine:

    public async Task CreateOrUpdateSimpleLine(List<DbSimpleLine> dbSimpleLines)
    {
        using (var context = new DDropContext())
        {
            foreach (var dbSimpleLine in dbSimpleLines)
            {
                var dbSimpleLineToUpdate = await context.SimpleLines.FirstOrDefaultAsync(x => x.SimpleLineId == dbSimpleLine.SimpleLineId);

                if (dbSimpleLineToUpdate != null)
                {
                    try
                    {
                        context.Entry(dbSimpleLineToUpdate).CurrentValues.SetValues(dbSimpleLine);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e.Message);
                    }
                }
                else
                {
                    context.SimpleLines.Add(dbSimpleLine);
                }
            }

            await context.SaveChangesAsync();
        }
    }

Когда я это делаю, я получаю исключение:

System.InvalidOperationException: 'Обнаружены конфликтующие изменения роли' DbDropPhoto_SimpleHor HorizontalLine_Target 'отношения' DDrop.Db.DbDropPhoto_SimpleHorizontLine ' . '

1 Ответ

2 голосов
/ 15 марта 2020

Вы должны явно определить свои внешние ключи, когда у вас есть несколько экземпляров одного и того же класса. что означает:

[Table("DropPhotos")]
public class DbDropPhoto
{
   [Key]
   public Guid DropPhotoId { get; set; }
   public int ZDiameterInPixels { get; set; }
   public int? SimpleHorizontalLineId { get; set; }
   [ForeignKey("SimpleHorizontalLineId")]
   public virtual DbSimpleLine SimpleHorizontalLine { get; set; }
   public int? SimpleVerticalLineId { get; set; }
   [ForeignKey("SimpleVerticalLineId")]
   public virtual DbSimpleLine SimpleVerticalLine { get; set; }
}

public class DbReferencePhoto
{
   [Key]
   public Guid ReferencePhotoId { get; set; }
   public Guid SimpleLineId { get; set; }
   [ForeignKey("SimpleLineId")]
   public virtual DbSimpleLine SimpleLine { get; set; }
}

[Table("SimpleLines")]
public class DbSimpleLine
{
   [Key]
   public Guid SimpleLineId { get; set; }
   public int? ReferencePhotoId { get; set;}
   [ForeignKey("ReferencePhotoId")]
   public virtual DbReferencePhoto ReferencePhoto { get; set; }
   public int? DropPhotoHorizontalLineId { get; set;}
   [ForeignKey("DropPhotoHorizontalLineId")]
   public virtual DbDropPhoto DropPhotoHorizontalLine { get; set; }
   public int? DropPhotoVerticalLineId { get; set;}
   [ForeignKey("DropPhotoVerticalLineId")]
   public virtual DbDropPhoto DropPhotoVerticalLine { get; set; }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...