Entity Framework circular dependency for last object

Pay attention to the following objects

public class What {
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Track> Tracks { get; set; }
    public int? LastTrackId { get; set; }]
    public Track LastTrack { get; set; }
}

public class Track {
    public Track(string what, DateTime dt, TrackThatGeoposition pos) {
        What = new What { Name = what, LastTrack = this };
    }

    public int Id { get; set; }

    public int WhatId { get; set; }
    public What What { get; set; }
}

I use the following to configure entities:

builder.HasKey(x => x.Id);
builder.HasMany(x => x.Tracks).
    WithOne(y => y.What).HasForeignKey(y => y.WhatId);
builder.Property(x => x.Name).HasMaxLength(100);
builder.HasOne(x => x.LastTrack).
    WithMany().HasForeignKey(x => x.LastTrackId);

You see that the requested circular link exists:

What.LastTrack <-> Track.What

when I try to add Trackto the context (actually on SaveChanges):

Track t = new Track("truc", Datetime.Now, pos);
ctx.Tracks.Add(t);
ctx.SaveChanges();

I get the following error:

It is not possible to save changes because a cyclic dependency was detected in the stored data: '' What '{' LastTrackId '} →' Track '{' Id '},' Track '{' WhatId '} →' What '{' Id '}' .

I would like to say ... yes, I know, but ...

Is this configuration applicable with EF Core?

+4
source share
1

, : , . ... .

What ( , , ?) Tracks , , LastTrack - , What .

What Track, EF What.Id, Track WhatId. What, Track. SQL , ​​ .

What Track What.LastTrackId.

, TransactionScope:

using(var ts = new TransactionScope())
{
    // do the stuff
    ts.Complete();
}

, ts.Complete(); , TransactionScope.

+4

Source: https://habr.com/ru/post/1657918/


All Articles