实体框架核心中的建模文件夹结构 [英] Modelling folder structure in Entity Framework Core

查看:115
本文介绍了实体框架核心中的建模文件夹结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将分层​​文件夹结构保存到SQL数据库中。课堂会这样:

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; }
}

我试图使用Entity Framework Core映射:

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:引入FOREIGN KEY约束'FK_Folders_Folders_ParentId'在表'文件夹'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束或索引。查看以前的错误。

在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,Boolean breakConnection,Action 1 wrapCloseInAction)

在System.Data。 SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,Boolean callerHasConnectionLock,Boolean asyncClose)

在System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean& dataReady)

在System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName,Boolean async,Int32 timeout,Boolean asyncWrite)

在System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery( TaskCompletionSource
1完成,Boolean sendToPipe,Int32 timeout,Boolean asyncWrite,String methodName)

在System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalC ommand.Execute(IRelationalConnection连接,String executeMethod,IReadOnlyDictionary 2 parameterValues,Boolean openConnection,Boolean closeConnection)

在Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection,IReadOnlyDictionary
2 parameterValues,Boolean manageConnection)

在Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands,IRelationalConnection连接)

在Microsoft .EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)

在Microsoft.EntityFrameworkCore.Design.MigrationsOperations.UpdateDatabase(String targetMigration,String contextType)

在Microsoft.EntityFrameworkCore。 Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String [] args)

在Microsoft中的工具.Cli.DatabaseUpdateCommand。  c__DisplayClass0_0.b__0()

.EntityFrameworkCore.Tools.Cli.Program.Main(String [] args)

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

错误编号:1785,状态:0,类别:16

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

介绍FOREIGN KEY约束'FK_Folders_Folders_ParentId'在表'文件夹'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
无法创建约束或索引。查看以前的错误。

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.

我也尝试映射没有关系2,但它工作,但是当我从数据库中加载项,它们返回为单

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?

推荐答案

您不需要任何映射配置。模型定义本身足以进行迁移,以生成正确的表结构,这将是一个称为 Id 的PK字段,以及一个名为 ParentId 。

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.

EF Core中背后的主体与EF 6相同。更多信息: http://www.mikesdotnetting.com/article/255/entity-framework -recipe-hierarchical-data-management

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

这篇关于实体框架核心中的建模文件夹结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆