Does Entity Framework support delete records and set the foreign key to null?

I have a model like this:

public class Account
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public Account Parent { get; set; }
}

and I will add the following configuration:

    this.HasOptional(item => item.Parent)
        .WithMany()
        .HasForeignKey(item => item.ParentId)
        .WillCascadeOnDelete(true);

and then I got the following error message:

UnitTest.Biz.Accounting.TestInitializer.Init assembly initialization method threw an exception. System.Data.SqlClient.SqlException: System.Data.SqlClient.SqlException: introducing the FOREIGN KEY constraint 'FK_dbo.acct_Account_dbo.acct_Account_ParentId' in the table "acct_Account" can cause loops or several cascading paths. Indicate ON DELETE NO ACTION or DO NOT UPDATE NO ACTION, or change another FOREIGN KEY of restriction. Failed to create constraint.

I read the EF docs, but I don't understand where is wrong in my code ...

, Code First , http://msdn.microsoft.com/en-us/data/jj591620#CascadeDelete

+4
1

SQL- .

, SQL Server , , . , , .

, EF .

.WillCascadeOnDelete(true); // Not allowed.

, Code First

- EF, api. ,

public int? ParentId { get; set; } // <--- nullable
public Account Parent { get; set; }

EF , WillCascadeOnDelete(false), , ON DELETE NO ACTION.

EF ON DELETE SET NULL, , .

, null.

, , .

+5

All Articles