I am doing a Code-first EF approach except for the fact that I am managing the database (for schema change issues that I believe still exist in code-first). I have the following tables / model objects (eliding several parameters, etc) :
class A {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual List<B> BList {get;set;}
public virtual List<C> CList {get;set;}
}
class B {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("A"), Required]
public int AId {get; set;}
public virtual A parent {get;set;}
public virtual List<D> DList {get;set;}
}
class C {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("A"), Required]
public int AId {get;set;}
[ForeignKey("someD"), Required]
public int someDId {get;set}
public virtual D someD
}
class D {
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("B"), Required]
public int BId {get;set;}
public string data {get;set;}
}
There's more to it than that, but the idea is that from a parent object A, I can navigate to a D along two different relationships. The Cascade delete relationships in the database are set up such that A->B, A->C, and B->D are cascades; C->D is 'no action'.
Therefore, when I go to delete an A (DbSet.Remove(a); SaveChanges(); etc ) EF needs to delete the C branch first, so that it can later delete the D's and not violate the FK constraint C->D. However, it appears to be choosing the other path, as the delete throws an exception about said constraint being violated. Is there a way for me to provide a hint (attribute or otherwise) to EF to tell it something else about these relationships so it can delete things in the right order?
edit Added more clarity to the approach in the co开发者_JAVA技巧de; Also, this thought occurs to me: I'm not explicitly capturing the relationship from C->D on D's end - that is, there is no navigation property on D that points to C; because C is a part of a Table-per-type scheme and not all D's point to a good collection of C's base class. Do I need to have some kind of navigation property in D back to C for EF to understand what I want?
精彩评论