Как обновить сущность с несколькими отношениями один-к-одному - PullRequest
0 голосов
/ 15 марта 2020

У меня есть объекты: DbDropPhoto, DbReferencePhoto и DbSimpleLine. DbSimpleLines используется bReferencePhoto и DbDropPhoto. Я хочу сделать DbSimpleLine связываемым только с одним из них, используя объекты для DbSimpleLine. Например, если DbSimpleLine равен DropPhotoHor horizontalLine, два других свойства будут нулевыми. Я искал какое-то решение и нашел это: http://csharpwavenet.blogspot.com/2013/06/multiple-foreign-keys-with-same-table.html Но теперь я действительно запутался. Например, согласно примеру мой класс DbSimpleLine должен иметь коллекцию ReferencePhoto, но на самом деле один DbSimpleLine может иметь только один ReferencePhoto. Я сделал что-то не так при настройке отношений? Для конфигурации отношений я использую свободный API:

        modelBuilder.Entity<DbDropPhoto>()
            .HasOptional(b => b.SimpleHorizontalLine)
            .WithMany(a => a.DropPhotoHorizontalLine)
            .HasForeignKey(b => b.SimpleHorizontalLineId)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<DbDropPhoto>()
            .HasOptional(b => b.SimpleVerticalLine)
            .WithMany(a => a.DropPhotoVerticalLine)
            .HasForeignKey(b => b.SimpleVerticalLineId)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<DbReferencePhoto>()
            .HasOptional(b => b.SimpleReferencePhotoLine)
            .WithMany(a => a.ReferencePhoto)
            .HasForeignKey(b => b.SimpleReferencePhotoLineId)
            .WillCascadeOnDelete(false);

.WithMany () смущает меня, потому что SimpleVerticalLine (например) не должен иметь много DropPhoto.

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

    public ICollection<DbReferencePhoto> ReferencePhoto { get; set; }
    public ICollection<DbDropPhoto> DropPhotoHorizontalLine { get; set; }
    public ICollection<DbDropPhoto> DropPhotoVerticalLine { get; set; }
}

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

    public Guid? SimpleReferencePhotoLineId { get; set; }
    public DbSimpleLine SimpleReferencePhotoLine { get; set; }
}

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

    public Guid? SimpleHorizontalLineId { get; set; }
    public DbSimpleLine SimpleHorizontalLine { get; set; }

    public Guid? SimpleVerticalLineId { get; set; }
    public DbSimpleLine SimpleVerticalLine { get; set; }
}

Также, когда я пытаюсь сохранить dbDropPhoto в базу данных, получаю исключение:

System.InvalidOperationException: 'Нарушено ограничение множественности. Роль 'DbDropPhoto_Drop_Target' отношения 'DDrop.Db.DbDropPhoto_Drop' имеет кратность 1 или 0..1. '

код для метода сохранения:

public async Task UpdatDropPhoto(DbDropPhoto dropPhoto)
{
    using (var context = new DDropContext())
    {
        var dropPhotoToUpdate = await context.DropPhotos.FirstOrDefaultAsync(x => x.DropPhotoId == dropPhoto.DropPhotoId);

        try
        {                  
            if (dropPhoto.SimpleVerticalLine != null)
                context.SimpleLines.Add(dropPhoto.SimpleVerticalLine);
            if (dropPhoto.SimpleHorizontalLine != null)
                context.SimpleLines.Add(dropPhoto.SimpleHorizontalLine);
            context.Entry(dropPhotoToUpdate).CurrentValues.SetValues(dropPhoto);

            await context.SaveChangesAsync();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
        await context.SaveChangesAsync();
    }
}

1 Ответ

1 голос
/ 16 марта 2020

Закончилось так:

       modelBuilder.Entity<DbDropPhoto>()
            .HasOptional(c => c.SimpleHorizontalLine)
            .WithMany()
            .HasForeignKey(s => s.SimpleHorizontalLineId);

        modelBuilder.Entity<DbDropPhoto>()
            .HasOptional(c => c.SimpleVerticalLine)
            .WithMany()
            .HasForeignKey(s => s.SimpleVerticalLineId);

        modelBuilder.Entity<DbReferencePhoto>()
            .HasOptional(c => c.SimpleReferencePhotoLine)
            .WithMany()
            .HasForeignKey(s => s.SimpleReferencePhotoLineId);

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

[Table("ReferencePhotos")]
public class DbReferencePhoto
{
    [Key]
    public Guid ReferencePhotoId { get; set; }     
    public Guid? SimpleReferencePhotoLineId { get; set; }
    [ForeignKey("SimpleReferencePhotoLineId")]
    public virtual DbSimpleLine SimpleReferencePhotoLine { get; set; }
}

[Table("DropPhotos")]
public class DbDropPhoto
{
    [Key]
    public Guid DropPhotoId { get; set; }
    public Guid? SimpleHorizontalLineId { get; set; }
    [ForeignKey("SimpleHorizontalLineId")]
    public virtual DbSimpleLine SimpleHorizontalLine { get; set; }
    public Guid? SimpleVerticalLineId { get; set; }
    [ForeignKey("SimpleVerticalLineId")]
    public virtual DbSimpleLine SimpleVerticalLine { get; set; }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...