We have an existing code-first database using .NET Framework 4.5.2 and Entity Framework 6.2.0 where models are defined in a separate classlib.
The DAL classlib defines its own models inheriting from the generic models.
In the DAL models the foreign keys are defined using the ForeignKey
attribute since sometimes the default naming convention cannot be applied.
We added a ScriptIgnore
attribute to the navigation properties in order to prevent serialization problems.
Everything works as expected, except that when adding a new migration it happens that "some" foreign keys are dropped, new columns are added with the default naming convention and foreign keys are applied to those new columns.
Just removing the ScriptIgnore
attribute the migration is fine and the foreign keys are all kept as they are.
Not all foreign keys are dropped and recreated this way, for example on the same table there are 3 foreign keys and none of them follow the naming convention, therefore are decorated with the ForeignKey
and ScriptIgnore
attribute, but only one of them is dropped and recreated by the migration.
We cannot figure out in which case the ForeignKey
attribute is not respected and what causes this behaviour.
public class Alarm
{
// ...
public int? idChannel { get; set; }
public int? idDevice { get; set; }
public int? idScenario { get; set; }
// ...
}
public class EFAlarm : Alarm
{
[ForeignKey("idChannel"), ScriptIgnore]
public virtual EFChannel Channel { get; set; } // This one is kept as is
[ForeignKey("idDevice"), ScriptIgnore]
public virtual EFDevice Device{ get; set; } // This one is kept as is
[ForeignKey("idScenario"), ScriptIgnore]
public virtual EFScenario Scenario { get; set; } // This one is dropped and recreated
}
Here an extract from the migration:
public override void Up()
{
// ...
DropForeignKey("dbo.fe_alarms", "idScenario", "dbo.scenario");
DropIndex("dbo.fe_alarms", new[] { "idScenario" });
AddColumn("dbo.fe_alarms", "Scenario_id", c => c.Int());
CreateIndex("dbo.fe_alarms", "Scenario_id");
AddForeignKey("dbo.fe_alarms", "Scenario_id", "dbo.scenario", "id");
// ...
}
The ScriptIgnore Attribute is defined in the System.Web assembly.
We tried using other custom attributed defined in different assembly but none of them seems to be causing this kind of problem.
What could be the cause of this behaviour?
question from:
https://stackoverflow.com/questions/65899437/scriptignore-attribute-in-entity-framework-6-breaks-foreign-key-attribute