Using Entity Framework code-first approach.
Suppose I have two entity classes:
[Table("Objects")]
public class DbObject : IValidatableObject
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<DbObjectProperty> Properties { get; set; }
}
[Table("ObjectProperties")]
public class DbObjectProperty
{
public long Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
[Display(Name = "Object"), UIHint("Object")]
public long ObjectId { get; set; }
public virtual DbObject Object { get; set; }
}
Points to note here:
DbObject
only has a navigation property, but no column with a foreign keyDbObjectProperty
has a navigation property and a corresponding column with a foreign key- It should be obvious that if I delete an object, I want its properties to go with it, but if I delete a single property, I don’t want the entire object to disappear.
In the OnModelCreating
method for the DB context, up until now I had the following to define the relationship:
modelBuilder.Entity<DbObjectProperty>()
.HasRequired(op => op.Object)
.WithMany(obj => obj.Properties)
.HasForeignKey(op => op.ObjectId)
.WillCascadeOnDelete(false);
Of course, this means no cascaded deletes will occur. My question is: if I change this to true
, does that do what I want? Remember if I delete an object, I want its properties to go with it, but if I delete a single property, I don’t want the entire object to disappear.
The auto-generated migration code for this change (from false
to true
) is this:
DropForeignKey("ObjectProperties", "ObjectId", "Objects");
DropIndex("ObjectProperties", new[] { "ObjectId" });
AddForeignKey("ObjectProperties", "ObjectId", "Objects", "Id", cascadeDelete: true);
CreateIndex("ObjectProperties", "ObjectId");
I am worried that this seems to imply that deleting a property will delete its associated object. Will it?