问题
I know that you set a nullable key in your entity if you want that FK to be nullable:
class ChildEntity
{
// Other properties not shown for brevity
public int? ParentId { get; set; }
public virtual ParentEntity Parent; { get; set; }
}
This will result in a nullable FK. It was suggested here that we should also set the optional relationship in Fluent:
modelBuilder.Entity<ChildEntity>()
.HasOptional(c => c.Parent)
.WithMany()
.HasForeignKey(c => c.ParentId);
but this still doesn't set delete set null. The FK ParentId still has delete set to No Action.
Later in the article, it was suggested that we should run the SQL command in the Seed method of the Configuration class? I'm not sure if it's a problem, but I run Update-Database quite often, and I'd be changing this setting back and forth.
So, is it safe, then, to "go behind EF's back" and change the delete rule to SET NULL in SQL Management Studio (or other app)? Since we're using SqlCommand in the seed method in plain SQL language, I want to say yes, we can go ahead and manually change the delete rule, but I'm not sure. I can't afford to experiment at this point, so I would appreciate an answer for this.
回答1:
That example puts the sql in the Seed method and that means that it runs every time you call Update-Database. You avoid that by making the modification to the database using the Sql method in a migration. That way it only runs once.
public void Up()
{
Sql(@"ALTER TABLE Products DROP CONSTRAINT Product_Category");
Sql(@"ALTER TABLE Products ADD CONSTRAINT Product_Category
FOREIGN KEY (CategoryId) REFERENCES Categories (CategoryId)
ON UPDATE CASCADE ON DELETE SET NULL");"
}
来源:https://stackoverflow.com/questions/27905338/since-ef-doesnt-support-delete-set-null-can-i-run-an-sql-command-outside-ef-to