Modelling folder structure in Entity Framework Cor

2020-08-04 10:05发布

问题:

I would like to save an hierarchical folder structure into a SQL database. The class would like this:

public class Folder
{
    public Folder()
    {
        Children = new List<Folder>();
    }

    public string Name { get; set;  }
    public int Id { get; set; }

    public int? ParentId { get; set; }
    public Folder Parent { get; set; }

    public ICollection<Folder> Children { get; set; }
}

I'm trying to map it using Entity Framework Core:

builder.Entity<Folder>()
       .HasKey(i => i.Id);

// Relation 1
builder.Entity<Folder>()
       .HasMany(e => e.Children)
       .WithOne(e => e.Parent)
       .HasForeignKey(e => e.ParentId);

// Relation 2
builder.Entity<Folder>()
       .HasOne(f => f.Parent)
       .WithMany(f => f.Children)
       .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Cascade);

If I try to update the database, I get the following exception:

System.Data.SqlClient.SqlException: Introducing FOREIGN KEY constraint 'FK_Folders_Folders_ParentId' on table 'Folders' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource
1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean openConnection, Boolean closeConnection)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary
2 parameterValues, Boolean manageConnection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Tools.Cli.DatabaseUpdateCommand.<>c__DisplayClass0_0.b__0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)

ClientConnectionId:f0c08167-fba7-4afa-baf0-45909e9a1f4b
Error Number:1785,State:0,Class:16

Introducing FOREIGN KEY constraint 'FK_Folders_Folders_ParentId' on table 'Folders' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.

I also tried mapping it without the 'Relation 2', it works but then when I load the items from database they return as single items with the Children property not set.

What is the correct way of storing such kind of data?

回答1:

You should't need any mapping configuration. The model definition is enough on its own for migrations to generate the correct table structure, which will be a PK field called Id, and a nullable FK field called ParentId.

The principal behind this in EF Core is the same as it is in EF 6. For more information: http://www.mikesdotnetting.com/article/255/entity-framework-recipe-hierarchical-data-management