Reputation: 1395
I have two classes. The class BC_Instance
can have many BC_InstanceSession
and a BC_InstanceSession
is dependent on a BC_Instance
and should be deleted when it's relative BC_Instance is deleted.
//Instance
public class BC_Instance
{
public int ID { get; set; }
//sessions
public ICollection<BC_InstanceSession> sessions { get; set; }
}
//Instance session
public class BC_InstanceSession
{
[Key]
public int ID { get; set; }
[ForeignKey("Instance")]
public int InstanceID { get; set; }
public virtual BC_Instance Instance { get; set; }
}
I have detected a few problems with this configuration. First Sessions are not deleted when it's Instance is deleted. Is it possible to specify that a session cannot exist without an instance or I need to manually delete them?
Second there seems to be a problem in the mapping to the database. A Session has two foreign keys on the Database InstanceID
and BC_Instance_ID
as show in the image below:
Finally Lazy loading does not work. Explicit loading is needed to access the Sessions for an instance (code below)
BC_Instance instance = db.BiocloudInstances.Include(i => i.sessions).Where(i => i.ID == id).First();
Upvotes: 0
Views: 48
Reputation: 1824
For the first question you can use a CascadeOnDelete
, something like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BC_Instance>()
.HasMany(i => i.sessions)
.WithRequired(s => s.Instance)
.WillCascadeOnDelete(true);
}
For the second one, if you look on the EntityFramework
documentation they specify that a 1-n relationship is used without the ForeignKey
adnotation. So, because you declare your relationship virtual, EF will add 2 keys. To fix this, remove the ForeignKey
adnotation and the public int InstanceID { get; set; }
row. (More on their page here)
Third, as i specified in the comment,
the lazy loading is not working because you didn't specify virtual
to your ICollection
. Like: public virtual ICollection<BC_InstanceSession> sessions { get; set; }
Upvotes: 1